I have a controller with method as follows:
public JsonResult Save(List<BlogInfo> list)
{
return Json(new { Data = "" }, JsonRequestBehavior.AllowGet);
}
And I have an ajax post from the client as follows:
$.ajax({
url: "Home/Save",
type: "post",
contentType: "application/json",
data: ko.mapping.toJSON(ViewModel),
success: function (response) {
alert(response.Status);
}
});
My problem is that list parameter to the controller is always null. I tried changing it to string instead of List but that is also null.
Using Fiddler, I can see that the JSON is being pass as follows:
{"Data":[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description","Tags":[]}]}
The JSON you have shown doesn't represent an array, so you cannot possibly expect to bind it to a list on the server. To achieve that make sure that you are sending an array of objects from the client:
data: ko.mapping.toJSON(ViewModel.Data);
Here we take the ViewModel.Data property which represents an array so that we send only the desired JSON:
[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description","Tags":[]}]
Related
I have been trying to send a list model to controller using ajax but it seems it is not working at all
Model
public string MyModel {
public string myfieldName {get;set;}
}
controller
public JsonResult Create(List<myModel> list)
{
return Json("Success");
}
post request
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC' }, { myfieldName: 'DEF' }];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: JSON.stringify({ list }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
so when I send this through, I check the browser and I can see that the request payload is sent with json object list
However when I go to controller the list is not binding it at all, so I check the http.context to check the request payload there and it all empty.
on the other hand when I change the controller like below
sending request with only model
public JsonResult Create(myModel data)
{
return Json("Success");
}
and change the js with below
$("body").on("click", "#btnSave", function () {
var data ={};
data.myfieldName= "test";
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: data,
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
the only difference here is that I don't send as json, so my question what is the is the difference between sending model vs a list of model using ajax
and what can I change to get the controller to bind the data or accept a list of model data
noting i'm using .Net core 2.0
Thank you
I usually use this method to send my Model as a List to my Controller method. I will try to show you regarding your scenario, how you can do this:
AJAX:
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC'}, { myfieldName: 'DEF'}];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "#Url.Action("Create","Project")",
data:{"json": JSON.stringify(list)},
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
And you can receive your Model like this in your Create method:
Make sure to import the System.Web.Script.Serialization namespace:
using System.Web.Script.Serialization
[HttpPost]
public JsonResult Create(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
List<string> myfieldName=new List<string>();
//Access your array now
foreach (var item in jsondata)
{
myfieldName.Add(item["myfieldName"]);
}
//Do something with the list here
return Json("Success");
}
Hope this helps you out.
Another method would be to utilize unobtrusive AJAX. All you would need is to install Microsoft jQuery unobtrusive AJAX from your Nuget Package Manager.
Then, in your view, call the following:
#{using (Ajax.BeginForm("Create", "ControllerName", null, new AjaxOptions()
{
HttpMethod = "POST",
// ...
}
}))
{
// Html code goes here
}
And also make sure that you include this at the bottom of your view:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Then, you can have a normal ActionResult setup (instead of JsonResult) for your controller and accept an argument of List list.
I would like to map a list of objects from client to server, using MVC. On the server I see that list is populated with correct number of items, but properties are empty. What am I doing wrong?
Here is the code from client:
var listCAORAS = [];
$('span.chkDelete input[type=checkbox]:checked').each(function (i, obj) {
var iORAS_KEY = $(obj).parent().attr('data-ioras_key');
if (iORAS_KEY) {
listCAORAS.push({ "iORAS_KEY": Number(iORAS_KEY) });
}
});
$.ajax({
method: 'post',
url: '/OrderSupplier/DeleteCAORAS/',
data: {
listCAORAS: listCAORAS
}
});
Server side:
public JsonResult DeleteCAORAS(List<DTO_CAORAS> listCAORAS)
{
}
public class DTO_CAORAS
{
public int? iORAS_KEY { get; set; }
//many more properties here
}
The default jQuery ajax contentType is 'application/x-www-form-urlencoded; charset=UTF-8' which means in order to bind to you model, the format of your data would need to be
$.ajax({
....
data: { [0].iORAS_KEY: 1, [1].iORAS_KEY: 1, [2].iORAS_KEY: 1, ... }
});
i.e your object names need to have zero-based, consecutive collection indexers.
Note that if your view is correctly generated (i.e. your checkboxes are bound to a bool property and you have a hidden input for the iORAS_KEY property), then all you would need is
$.ajax({
....
data $(yourForm).serialize()
});
To send an array of complex objects as you are doing, you must set the contentType to 'json' and stringify the data which instructs the DefaultModelBinder to use the JsonValueProviderFactory to deserialize the data to your model.
$.ajax({
url: '#Url.Action("DeleteCAORAS", "OrderSupplier")', // always use Url.Action() to generate the url
....
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ listCAORAS: listCAORAS })
});
I have this basic quiz app that I'm trying to build and right now I'm stuck on processing the submitted quiz answers in spring.
I use a js function to store the question id and submitted answers id's in a json object like so:
{
1: [2,3,4],
2: [1,2]
}
So, the user sent the answers 2,3,4 for the question with the id of 1. Now, I'm trying to send this json object to the spring controller method using ajax.
// DO POST
function ajaxSubmitAns(formdata){
$.ajax({
type : "POST",
url : "/process-answers",
data: JSON.stringify(formData),
contentType : 'application/json; charset=utf-8',
dataType: 'json',
headers: {
Accept: 'application/json'
},
success: function(){
//do something
},
error : function(e) {
//error
}
});
}
I also wrote the controller function but what I don't know is how do I access these values from the json object. How can I loop through the keys (questions id's) and get the values?
What I have for the controller is this so far:
#RequestMapping(value = "/process-answers", method = RequestMethod.GET)
#SuppressWarnings("unchecked")
public #ResponseBody
String processQuizz(#RequestBody String json) {
}
#PostMapping("/process-answers")
#ResponseBody
public void processQuizz(#RequestBody Map<Integer, List<Integer> quiz) {
quiz.forEach((quizId, answers) -> ... your business logic here ...);
}
Now you can iterate through your map directly without json processing.
I am working with mvc4 application. I developed a form using .cshtml file, which inherits the model and has its corresponding controller action.
I am submitting the form using a ajax jquery like,
var body=$('#formId').serialize();
$.ajax({
url: submitAction,
type: "POST",
datatype: "json",
data: body,
success: function (data) {
if (data != null) {
alert("success");
}
});
"body" is fine and it has serialized data and the submitAction is the var which holds my controller action and the controll is transfered there.
EDIT:
My controller looks like,
public JsonResult(ParentModel model) /*here model always hold null values, WHY??*/
{
//stmts..
return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
}
But, there the parameter of my controller action is showing null values. Can someone tell what could be the mistake and how can I resolve it?
$.ajax({
url: submitAction,
type: "POST", <-- you make post, but asp.net mvc controller receives default GET request
data: { model: body},
[HttpPost]
public JsonResult(string model) //<--now you pass string and to Deserialize in ParentModel
{
JavaScriptSerializer jss= new JavaScriptSerializer();
ParentModel pmodel = jss.Deserialize<ParentModel >(model);
return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
}
Try edit data: section in you request,
remove datatype: "json"
And edit type model parameter to string
my problem is following.
I try to parse some data via ajax, passing the data to my controller:
AJAX
$.ajax({
type: "GET",
url: "ParseOrganizaitonPath",
data: {
organizationPath: $('#organizationPath').val()
},
success:
function (data) {
//data is from type string with value "System.string[]"
//but should be from type System.string[]
});
}
});
Controller
public string[] ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
return organizations.ToArray();
}
I am reaching the controller method and in it everything is fine, but the data that is comming back (ajax part, success method) is just a string ("System.string[]", data[0] S, data[1]y data[2]s...) but not the data I want. (For example if i pass the input "test/one" I want to have as result data[0] test, data[1] one)
Hope you understand what my Problem is.
Thanks in advance!
Julian
Have to tried to use the JavaScriptSerializer? Have a look at this example:
public string ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
return oSerializer.Serialize(organizations);
}
To deserialize the JSON string with JavaScript you can use the parse function:
var array = JSON.parse(data);
I found a way where you don't have to serialize it (on c# site) and parse it (on javascript site)
Just use the JSON Method that is inherited from the Controller and return an JsonResult:
public JsonResult ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
return JSON(organizations);
}
On the client site (javascript) you have to use JSON.stringfy(dataObject) for data that you want to send to your controller-method.
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "ParseOrganizaitonPath",
data: JSON.stringify(myDataObject),
success:
function (data) {
//use your data
});
}
});
That's how it worked for me.
Good luck!
Julian