When I ajax post json data but also received null - ajax

I try so many times to do below these code . but it still recive the value is null.
var cartViewModel = [];
$(":text").each(function (i) {
var quantity = parseInt($(this).val());
var id = parseInt($(this).data("id"));
cartViewModel.push({ id: id, quantity: quantity });
}
and next I use $.post to submit cartViewModel
the code such like:
var data= { data: JSON.stringify(cartViewModel) };
$.post(url,data,function(json){
//....
});
public class ShoppingCartViewModel
{
public int Id { get; set; }
public int Quantity { get; set; }
}
[HttpPost]
public ActionResult SubmitCart(List<ShoppingCartViewModel> models)
{
return Json(result);
}
but the arg 'models' also is null, I feel very confused. who can point out the right way. thx!

The model binder is expecting a property named models, but you're using the name data. What happens if you change
var data= { data: JSON.stringify(cartViewModel) };
to
var data= { models: JSON.stringify(cartViewModel) };
Edit:
The reason your models property is now empty is because you're calling JSON.stringify(cartViewModel). Instead of passing the action an array of objects, your passing it a string (that happens to be a representation of an array of objects).
Change your data definition to:
var data = { models: cartViewModel };
Edit again:
The above works fine for MVC5. It does not work in MVC4. To make it work in MVC4:
$.ajax({
type: 'POST',
url: '#Url.Action("Add", "Home")',
data: JSON.stringify({ models: cartViewModel }),
contentType: 'application/json',
});

Related

Null parameter when use Ajax post

I have found several answers (here for example) but they do not seem to solve my problem.
var result = {
command: 'exportWAV',
type: type
};
$.ajax({
url: 'SubmitSound',
type: 'Post',
data: JSON.stringify(result),
contentType: 'application/json; charset=utf-8',
success: function (msg) {
alert(msg);
}
});
Back end code
[HttpPost]
public ActionResult SubmitSound(string blob)
{
// Create the new, empty data file.
string fileName = AppDomain.CurrentDomain.BaseDirectory + "/Content/Sound/" + Environment.TickCount + ".wav";
FileStream fs = new FileStream(fileName, FileMode.CreateNew);
BinaryWriter w = new BinaryWriter(fs);
w.Write(blob);
w.Close();
fs.Close();
return new JsonResult() { Data = "Saved successfully" };
}
result is not null because this.postMessage = result; send a file back to client side for downloading. w.Write(blob) keeps complaining that blob cannot be null.
How can I make it work? Thank you and best regards
Do this:
data: JSON.stringify({ blob: result}),
You may want to change your string param in your controller action, for an object with the same structure of your JSON... that means the same attributes names.
The object should be something like this:
public class MyBlob{
public string command {get; set;}
public string type {get; set;}
}
So, your action should be:
public ActionResult SubmitSound(MyBlob blob){
//Here your action logic
}

Pass List from view to controller

i am trying to pass List from view to controller but i am getting null value. code is written as follows :
model class :
public class testModel
{
public int ID { get; set; }
public string Name { get; set; }
public List<myModel> ParameterList {get;set;}
}
jquery and ajax code to post data to controller :
var myModel = {
"Name":"test",
"Description":"desc"
};
var Object = {
Name: $("#Name").val(),
ParameterList : myModel
};
$.ajax({
url: '/controller/action',
type: 'POST',
data: JSON.stringify(Object),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) { }
else { }
}
});
i am getting value for Name property but not for ParameterList.
What is wrong here ? am i missing anything ?
Please help me out.
Thanks
Edit : Controller Code from comments,
public JsonResult Save(Object Obj)
{
// logic for managing model and db save
}
You said,
I am getting value for Name property but not for ParameterList.
Which makes me wonder what is the structure of myModel, as you have declared ParameterList as a list of myModel type : List<myModel> ParameterList
Also I would recommend you to log JSON.stringify(Object) to console and check the Json value you are actually posting to the controller.
Here is what I found you must be posting back
{"Name":"yasser","ParameterList":{"Name":"test","Description":"desc"}}
Also read these articles :
How can I pass complex json object view to controller in ASP.net MVC
Pass JSON object from Javascript code to MVC controller
Try this:
var myModel = [{
"Name":"test",
"Description":"desc"
}];
var Object = {
Name: $("#Name").val(),
ParameterList : myModel
};
$.ajax({
url: '/controller/action',
type: 'POST',
data: Object,
dataType: 'json',
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) { }
else { }
}
});
Just try like this..Hope this would help!!
script:
var emp = [{ 'empid': 1, 'name': 'sasi' },{ 'empid': 2, 'name': 'sathish'}];
emp = JSON.stringify(emp)
$.post("/Home/getemplist/", { 'emp': emp })
Controller:
Here i just changed the parameter to string type. using JavaScriptSerializer you can able to convert this string data to your class list objects.. you can understand it better if u see my code below:
public void getemplist(string emp)
{
List<Emp> personData;
JavaScriptSerializer jss = new JavaScriptSerializer();
personData = jss.Deserialize<List<Emp>>(emp);
// DO YOUR OPERATION ON LIST OBJECT
}

Nested models don't bind

I want to pass a JSON data structure to an MVC (3) Controller, have the JSON object be translated into a C# object, with all properties bound. One of the properties is a simple Type. That's basic model binding, right?
Here are my models:
public class Person
{
public string Name { get; set; }
public JobTitle JobTitle { get; set; }
}
public class JobTitle
{
public string Title { get; set; }
public bool IsSenior { get; set; }
}
Here is my Index.cshtml page (which makes an AJAX request, passing in a JSON object which matches the strcture of the "Person" class):
<div id="myDiv" style="border:1px solid #F00"></div>
<script type="text/javascript">
var person = {
Name: "Bob Smith",
JobTitle: {
Title: "Developer",
IsSenior: true
}
};
$.ajax({
url: "#Url.Action("ShowPerson", "Home")",
data: $.param(person),
success: function (response){
$("#myDiv").html(response);
},
error: function (xhr) {
$("#myDiv").html("<h1>FAIL</h1><p>" + xhr.statusText + "</p>");
}
});
</script>
And my HomeController looks like this:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ShowPerson(Person person)
{
return View(person);
}
}
Ignore the "ShowPerson.cshtml" file for now because the problem occurs before that is ever needed.
In the HomeController.ShowPerson action, the "person.Name" property is correctly bound and the "person.JobTitle" object (containing "Title" and "IsSenior" properties) is instantiated but still has the default values of "Title = null" and "IsSenior = false".
I'm sure I have done nested model binding without problem in the past. What am I missing? Can anybody shed any light on why model binding only seems to work one level deep?
I've searched SO, and it seems everybody else is having binding problems when sending data from forms, so maybe I'm missing something in my $.ajax() request?
ok, there are couple of changes you need to do,
Set dataType as json
Set the contentType as application/json; charset=utf-8.
Use JSON.stringify()
below is the modified code. (tested)
var person = {
Name: "Bob Smith",
JobTitle: {
Title: "Developer",
IsSenior: true
}
};
var jsonData = JSON.stringify(person);
$.ajax({
url: "#Url.Action("ShowPerson", "Home")",
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (response){
$("#myDiv").html(response);
},
error: function (xhr) {
$("#myDiv").html("<h1>FAIL</h1><p>" + xhr.statusText + "</p>");
}
});
Add the content type to the ajax
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
data: $.toJSON(person);

Parameter to Web Service via Jquery Ajax Call

I am using revealing module pattern and knockout to bind a form. When data is entered in that form(registration), it needs to be posted back to MVC4 web method.
Here is the Jquery code
/*
Requires JQuery
Requires Knockout
*/
op.TestCall = function () {
// Private Area
var _tmpl = { load: "Loading", form: "RegisterForm"};
var
title = ko.observable(null)
template = ko.observable(_tmpl.load),
msg = ko.observable(),
postData = ko.observable(),
PostRegistration = function () {
console.log("Ajax Call Start");
var test = GetPostData();
$.ajax({
type: "POST",
url: obj.postURL, //Your URL here api/registration
data: GetPostData(),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8'
}).done(Success).fail(Failure);
console.log("Ajax Call End");
},
GetPostData = function () {
var postData = JSON.stringify({
dummyText1: dummyText1(),
dummyText2: dummyText2(),
});
return postData;
}
return {
// Public Area
title: title,
template: template,
dummyText1: dummyText1,
dummyText2: dummyText2
};
}();
The controller code is simple as per now
// POST api/registration
public void Post(string data)
{
///TODO
}
When i am trying to, capture the data (using simple console.log) and validate it in jslint.com, it's a valid Json.
I tried hardcoding the data as
data: "{data: '{\'name\':\'niall\'}'}",
But still i get as null, in my web method.
Added the tag [System.Web.Script.Services.ScriptMethod(UseHttpGet = false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] to my Post method in controlled, but still no fruitful result
Even tried JSON.Stringify data: JSON.stringify(data) but still i get null in my web-method.
I am not able to figure out the solution.
Similar issue was found # this link
http://forums.asp.net/t/1555940.aspx/1
even Passing parameter to WebMethod with jQuery Ajax
but didn't help me :(
MVC and WebApi uses the concept of Model Binding.
So the easiest solution is that you need to create a Model class which matches the structure of the sent Json data to accept the data on the server:
public void Post(MyModel model)
{
///TODO
}
public class MyModel
{
public string DummyText1 { get; set; }
public string DummyText1 { get; set; }
}
Note: The json and C# property names should match.
Only escaped double-quote characters are allowed, not single-quotes, so you just have to replace single quotes with double quotes:
data: "{data: '{\"name\":\"niall\"}'}"
Or if you want to use the stringify function you can use it this way:
data: "{data: '" + JSON.stringify(data) + "'}"

json ajax complex type pass to MVC2 action

I know this has been asked before in a similar form, but I have hit a bit of problem here....
I have this classic problem of trying to pass a json complex type to MVC2.
The problem (refer to the code below): I can pass the value "subincidentID" to the controller but the values "CodeType", "MOCode" and "SubCode" are all NULL.
I HAVE installed the MVC2 future and registered "Microsoft.Web.MVC" in global.asax.cs and declare the JsonValueProviderFactory.
The JQuery bit:
$('#btnDone').click(function() {
var entity = {};
var dbCode = new Array();
dbCode[0] = { CodeType: "1", MoCode: "13", SubCode: "12" };
entity = { subincidentID: "1", codeData: dbCode };
$.ajax({
type: 'POST',
data: entity,
dataType: 'json',
async: false,
url: "/controller/SaveMOData",
success: function(result) {
alert('success!');
}
}); //end of post
}); //end of btnDone click function
Controller in MVC:
[HttpPost]
public JsonResult SaveMOData(MOSubMitModel mo)
{
if (ModelState.IsValid)
{
}
return Json(new { success = "true" });
}
Model class in MVC (2):
public class MOSubMitModel
{
public int subIncidentID { get; set; }
public List<dbCode> codeData { get; set; }
}
public class dbCode
{
public string CodeType { get; set; }
public string subCode { get; set; }
public string MoCode { get; set; }
}
Have I missed something here?
Do I have to declare any namespace on the controller page?
I am sure it is a small problem but I have been scratching my head the whole day about it....:-(..
Thanks in advance.
W. Lam
I've heard of issues using the following syntax
$.ajax({
type: "POST",
data: {prop:"Value"},
....
}
Instead you need to stringify the object
$.ajax({
type: "POST",
data: JSON.stringify({prop:"Value"}),
....
}
After some more trial-and-error and readings I have finally figured it out myself (Refer to the previous posting for details of the other components):
$('#btnDone').click(function() {
:
:
$.ajax({
type: 'POST',
data: JSON.stringify(entity),
contentType: 'application/json',
async: false,
url: "/controller/SaveMOData",
success: function(result) {
alert('success!');
}
}); //end of post
}); //end of btnDone click function
The problem was me NOT to include "contentType" (I had tried to inclide json stringify before but it ALL returns NULL if I do not include contentType)...so...to summarise the requirements under MVC2:
Download MVC Future .....Unzip the MVC future zip file and copy Microsoft.web.mvc to your project, and reference it In your project's global.asax.cs file, include the "Microsoft.web.mvc" namespace, and then include the following line at the end of the function "Application_start"
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
Make the necessary changes in your jQuery as indicated above. It should be working (well it works for me!!)..Hope it helps anyone with the same problem.

Resources