Pass List from view to controller - asp.net-mvc-3

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
}

Related

When I ajax post json data but also received null

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',
});

MVC Controller post json does not work

I have the this code to post json to a controller.
The problem is that the credentials object does not get populated with the posted values.
How do I change this code so that it works?
I see in Fiddler that the request is being posted correctly.
[HttpPost]
public JsonResult Authenticate(CredentialsModel credentials)
{
return Json(credentials);
}
[DataContract]
public class CredentialsModel
{
[DataMember(Name = "user")]
public string User;
[DataMember(Name = "pass")]
public string Pass;
}
$.ajax({
type: "POST",
url: "/login/authenticate",
cache: false,
contentType: "application/json; charset=utf-8",
data: '{"user":' + JSON.stringify($('#username').val()) + ',"uass":' + JSON.stringify($('#userpass').val()) + '}',
dataType: "json",
timeout: 100,
success: function (msg) {
},
complete: function (jqXHR, status) {
if (status == 'success' || status == 'notmodified') {
var obj = jQuery.parseJSON(jqXHR.responseText);
}
},
error: function (req, status, error) {
}
});
The default MVC model binder only works with properties. Your CredentialsModel is using fields. Try changing them to properties. You can also remove the annotations.
public class CredentialsModel
{
public string User { get; set; }
public string Pass { get; set; }
}
Also, as pointed out by Sahib, you can create a Javascript Object and then stringify it, rather than stringifying each one. Although that doesn't appear to be the problem in this case.
data: JSON.stringify({
User: $('#username').val(),
Pass: $('#userpass').val()
})
Try chaning your data like this :
$.ajax({
.................
//notice the 'U' and 'P'. I have changed those to exactly match with your model field.
data: JSON.stringify({User: $('#username').val(),Pass: $('#userpass').val()}),
.................
});

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);

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.

Post jqgrid data to mvc3 controller

How should I post the data entered in a jqgrid plugin to a MVC3 controller?
Thanks In Advance
Some code
Sending data to mvc3 controller
var lineas = $("#articulosIngresadosTable").getRowData();
var model = {
ObraSocialId: $("#idObraSocialTextBox").val(),
Lineas: lineas
};
$.ajax({
type: 'POST',
url: '#Url.Action("Nueva", "Factura")',
data: model,
success: function (data) { alert(JSON.stringify(data)); },
dataType: "json"
});
The controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Nueva(FacturaNuevaModel model)
{
return Json(model);
}
The model
public class FacturaNuevaModel
{
public string ObraSocialId { get; set; }
public IList<Linea> Lineas { get; set; }
What I can't undestand is that I'm sending the same Json with Poster and works, but not whit jquery from the view
Using the post from the view, ObraSocialId is populated in the controller, and the Lineas collection have the items, but every property in Linea has a null value
The problem was the contentType ...
Here is the working code
var lineas = $("#articulosIngresadosTable").getRowData();
var model = {
ObraSocialId: $("#idObraSocialTextBox").val(),
Lineas: lineas
};
var modelString = JSON.stringify(model);
$.ajax({
type: 'POST',
url: '#Url.Action("Nueva", "Factura")',
data: modelString,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) { alert(JSON.stringify(data)); }
});

Resources