I am using MVC3 and that i know MVC3 support binding JSON literal to Action parameter. But i can't do it successfully;
I have a class name Tag
public class Tag
{
public int tagId { get; set; }
public string tagName { get; set; }
}
An Action on controller called Tag
[HttpPost]
public ActionResult Tag(Tag tag)
{
// Here will be codes...
return Json(new { success = 0 });
}
Javascript code that send js object as JSON to my action
var tag ={tagId:5,tagName:"hello"};
$.ajax({
url: "/image/tag",
type: "POST",
data: $.toJSON(tag),
success: function (r) {
if (r.success == 1) {
window.location = r.redirect;
}
}
Post Data that I see in Firebug Net tab
{"tagId":5,"tagName":"hello"}
Parameter name tag in Tag Action is not null but has values O for tagId and null for tagName. What the problem in here?
You need to set the content type of the request to application/json
:
$.ajax({
url: '/image/tag',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: $.toJSON(tag),
success: function (r) {
if (r.success == 1) {
window.location.href = r.redirect;
}
}
});
Ah, and you don't need to have your Tag model properties start with a lowercase letter:
public class Tag
{
public int TagId { get; set; }
public string TagName { get; set; }
}
Remark 1: The JavaScriptSerializer
class that ASP.NET MVC 3 uses behind the scenes is capable of properly handling this.
Remark 2: In your Tag
action you seem to be returning the following JSON: {"success":0}
whereas in your success AJAX callback you seem to be using some r.redirect
property which doesn't exist.
Remark 3: Avoid naming your controller actions the same way as your view models. Normally action names should represent verbs (like List
, Save
, Delete
, ...) whereas view models represent resources (TagModel
, ...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With