I have the following jQuery code in a View in MVC3. I want to load a partial view (named OffshoreECore) in a div (#Form) depending on the JSON object passed in the success function. Here's the code:
var inputParamtrs = { 'HeadId': $('#ExpenseId').val(), MProjid': $('#MProjid').val() };
$.ajax({
type: "POST",
url: "/Expenses/Edit",
data: inputParamtrs,
success: function (json) {
('#Form').load('#Url.Action("OffShoreECore", *What comes here ?!?*)');
}
Thanks.
The second parameter of load() is the data which should be sent to the specified URL along with the request. To send your JSON string, try this:
success: function (json) {
$('#Form').load('#Url.Action("OffShoreECore")', json);
}
You example code is also missing a ' delimiter from the second key in inputParamtrs and the $ from the selector in success, but I guess they're just typos.
$.getJSON("/Expenses/Edit",
{
HeadId: $('#ExpenseId').val(),
MProjid: $('#MProjid').val()
},
function (data) {
elementForResult.innerHTML = data;
});
In Controller:
public JsonResult Edit(int HeadId, int MProjid)
{
...
var result = SerializeControl("~/Views/Expenses/Edit.cshtml", null);
return Json(result, JsonRequestBehavior.AllowGet);
}
private string SerializeControl(string controlPath, object model)
{
var control = new RazorView(ControllerContext, controlPath, null, false, null);
ViewData.Model = model;
var writer = new HtmlTextWriter(new StringWriter());
control.Render(new ViewContext(ControllerContext, control, ViewData, TempData, writer), writer);
string value = writer.InnerWriter.ToString();
return value;
}
Related
i need to get data sent with JSON and save to model in asp.net controller
//JSON data
var dataType = 'application/json';
var data = {
ID: 'Zaki',
}
console.log('Submitting form...');
console.log(data);
$.ajax({
type: 'POST',
url: 'Save',
dataType: 'json',
contentType: dataType,
data: data,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
});
Controller
[HttpPost]
public ActionResult Save([FromBody] string ID)
{
return Json (ID);
}
am getting null in console , it supposed to be zaki and from there i wanna write saving code...
Another way to do it is to simply use 'dynamic' type to handle json request data. Take a look:
[HttpPost]
public IActionResult YoutMethod([FromBody] dynamic requestData)
{
Log.Information(requestData.field1);
Log.Information(requestData.field2);
// ...
return Ok();
}
Modify this line in your code data: data, to
data:JSON.stringify(data)
When sending data to a web server, the data has to be a string and JSON.stringify method converts a JavaScript object into a string.
Another approach would be, instead of getting raw string value, wrap your parameter into a class object like this
public class ParamObj
{
public string ID{get;set;}
}
and in your controller get a parameter of this object type like this..
public ActionResult Save([FromBody] ParamObj data)
Thanx
I know that is already marked as answered, but here is another way to do it:
I am not using the binding FromBody attribute.
Controller
public class JsonRequest
{
public string Id { get; set; }
}
[HttpPost]
public ActionResult Save(JsonRequest data)
{
return Json(data.Id);
}
Instead of using dataType I am using accept and you don't need to convert your json into a string.
To avoid problems with relative paths I am using: url: '#Url.Action("Save", "Home")' as well.
Javascript
function send()
{
//JSON data
var dataType = 'application/json';
var data = {
"id": "Zaki"
}
console.log('Submitting form...');
console.log(data);
$.ajax({
type: 'POST',
url: '#Url.Action("Save", "Home")',
accept: dataType,
data: data,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
});
}
Good luck with your project.
Could you please let me know how to extract JSON data received in a string variable in controller. Please see the attachment.Thanks.
$("#btn1").on("click", function () {
var i = new Array();
var j = 0;
$("#sl1").multiselect("getChecked").map(function () {
alert(this.value);
i.push(this.value);
//i[j] = this.value;
//j++;
}).get();
var postData = { values: i };
jQuery.ajaxSettings.traditional = true;
$.post('/TodoList/searchdata', postData, function (data) {
alert(data.Result);
});
//$.ajax({
// type: "POST",
// url: "/TodoList/searchdata",
// data: postData,
// success: function (data) {
// alert(data.Result);
// },
// dataType: "json",
// traditional: true
//});
});
Controller code:-
public void searchdata(String[] values)
{
//{
// JavaScriptSerializer js = new JavaScriptSerializer();
// List<String[][]> data=js.Deserialize<List<String[][]>>(i);
Console.WriteLine(values);
}
You can use Newtonsoft Json library https://www.nuget.org/packages/Newtonsoft.Json/
So As mentioned in the below link use it like below
string json = #"{ 'Email': 'james#example.com', 'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z', 'Roles': [
'User', 'Admin' ] }";
Account account = JsonConvert.DeserializeObject(json);
if you doesn't have model , just use like below
var model = JsonConvert.DeserializeObject(json);
the check the below link
http://www.newtonsoft.com/json/help/html/deserializeobject.htm
Try this
JavaScriptSerializer js = new JavaScriptSerializer();
var data=js.Deserialize<Dictionary<string, List<string>>>(i);
Use This Class :
public class JsonAttributeClass<T> where T:class ,new()
{
public static string EntityToJsonConvertor(T entity)
{
string json = JsonConvert.SerializeObject(entity);
return json;
}
public static T JsonToEntityConvertor(string json)
{
var entity = JsonConvert.DeserializeObject<T>(json);
return entity;
}
}
I have a simple function that searches for item I want in my database and retrieves it in my controller.
[HttpPost]
public ActionResult Index(string searchString)
{
var user = from m in db.Users select m;
if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.UserName.Contains(searchString));
}
return View(user);
}
And then in my Javascript I send a value to search:
$('#test').click(function(e) {
e.preventDefault();
var user = "John";
$.ajax({
url: "#Url.Action("Index", "Users")",
data { "searchString": user },
type: "post",
success: function (saveResult) {
console.log(saveResult);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr, ajaxOptions, thrownError);
}
})
})
However of course all this does it return my view inside the console window which is something like:
But I would like to return a json object I can use.
just use the Json Action method.
return Json(user);
Edit:
As a side note, I would also set my return Type to be JsonResult for clarity
You just return as JsonResult such as below:
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
I have a Spring MVC web application and I have the following web service.
#RequestMapping(value = "/newBill", method = RequestMethod.POST)
public #ResponseBody ModelMap acceptNewBill(#ModelAttribute ("Bill") Bill newBill ){
Bill bill = new Bill();
bill.setTableName(newBill.getTableName());
bill.setRoom(newBill.getRoom());
bill.setCovers(newBill.getCovers());
ModelMap model = new ModelMap();
model.put("status", true);
return model;
}
The following Script performs the front end functions.
$('.done').click(function(){
var jsonObject = createJSON(".newBill");
jQuery.ajax({
url: "/newBill",
type: "POST",
data: {bill: JSON.stringify(jsonObject) },
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});
});
function createJSON(elementToConvert) {
jsonObj = [];
$( elementToConvert + " input").each(function() {
var id = $(this).attr("class");
var email = $(this).val();
item = {}
item [id] = email;
jsonObj.push(item);
});
return jsonObj;
}
The above createJSON function go through a provided html element and puts the values into an object! The click function performs the POST and the Post contains the following data.
bill [{"tableName":"326432"},{"room":"3462346"},{"covers":"3426234"}]
Now when I debug and check the service, the data which goes from the front end doesn't get mapped in the parameter. I checked whether the variable names are the same as the POST. They are the same! but the values doesn't get mapped! Can any one please help me with this issue.
Update :
I changed the service method to GET and passed a value as a URL variable. Then it got mapped in the service param. The problem is in the POST.
Instead of using #ModelAttribute in your controller use #RequestBody:
public #ResponseBody ModelMap acceptNewBill(#RequestBody Bill newBill) {
On the ajax call, set the content type to application/json and stringify the whole object instead of just the array:
jQuery.ajax({
url: "/newBill",
type: "POST",
data: JSON.stringify({bill: jsonObject}),
dataType: "application/json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});
I'm using MVC web Api for RESTful purpose. My controller methods return serialized Json object in string format. I've got some simple method like this:
public string Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name= folder.Name};
var jsSerializer = new JavaScriptSerializer();
return jsSerializer.Serialize(folder1);
}
I call Get, Put, Delete and Post methods in QUnit test like this and it works fine:
ajax: {
getData: function (url, data) {
return processRequest(url, data, "GET");
},
postData: function (url, data) {
return processRequest(url, JSON.stringify(data),"POST");
},
updateData: function (url, data) {
return processRequest(url, JSON.stringify(data),"UPDATE");
},
deleteData: function (url, data) {
return processRequest(url, JSON.stringify(data),"DELETE");
},
processRequest: function (url, data, type) {
return $.ajax({
type: type,
dataType: "json",
contentType: "application/json;charset=utf-8",
url: url,
data: data,
processData: true
});
}
},
I need to change return value from string to actual Json object because my client doesn't want serialized Json anymore. They need actual Json object. So I changed the method return type to JsonValue and parse the serialized Json object using JsonValue.Parse() method. When I trace my codes in server side, JsonValue object has proper values in its properties and looks fine but the returned JsonValue in client side has empty properties. here is changed method:
public JsonValue Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name= folder.Name};
var jsSerializer = new JavaScriptSerializer();
return JsonValue.Parse(jsSerializer.Serialize(folder1));
}
here is test result:
Expected:
{
"Id": "1",
"IsShared": true,
"Name": "abc"
}
Actual:
{
"Id": [],
"IsShared": [],
"Name": []
}
I appreciate any idea.
What I did to fix is adding Newtonsoft.Json.dll to my project and using Newtonsoft.Json.Linq.JToken instead of using System.Json.JsonValue. here is my method implementation:
public Newtonsoft.Json.Linq.JToken Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name = folder.Name};
var jsSerializer = new JavaScriptSerializer();
return Newtonsoft.Json.Linq.JObject.Parse(jsSerializer.Serialize(folder1));
}
and if you have an array of JSON, you need to parse like this:
public Newtonsoft.Json.Linq.JToken Put(IList<Folder> folders)
{
var folder1 = new Folder{Id="1", IsShared=true,Name = folder.Name};
var jsSerializer = new JavaScriptSerializer();
return Newtonsoft.Json.Linq.JArray.Parse(jsSerializer.Serialize(folders));
}