Asp.Net MVC 3 JSON 模型绑定不起作用
我正在使用 MVC3 并且我知道 MVC3 支持将 JSON 文字绑定到 Action 参数。但我无法成功;
我有一个类名 Tag
public class Tag
{
public int tagId { get; set; }
public string tagName { get; set; }
}
控制器上的一个名为 Tag 的操作
[HttpPost]
public ActionResult Tag(Tag tag)
{
// Here will be codes...
return Json(new { success = 0 });
}
Javascript 代码将 js 对象作为 JSON 发送到我的操作 我
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;
}
}
在 Firebug Net 选项卡中看到的发布数据 标签
{"tagId":5,"tagName":"hello"}
操作中的参数名称标签不为 null,但 tagId 的值为 O,tagId 的值为 null标签名称。 这里有什么问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将请求的内容类型设置为
application/json
:啊,您不需要让您的 Tag 模型属性以小写字母开头:
备注 1:
JavaScriptSerializer ASP.NET MVC 3 在幕后使用的
类能够正确处理此问题。备注 2:在您的
Tag
操作中,您似乎返回以下 JSON:{"success":0}
而在您的 success AJAX 回调中,您似乎使用了一些 < code>r.redirect 属性不存在。备注 3:避免以与视图模型相同的方式命名控制器操作。通常,操作名称应代表动词(例如
List
、Save
、Delete
等),而视图模型则代表资源(TagModel< /代码>,...)。
You need to set the content type of the request to
application/json
:Ah, and you don't need to have your Tag model properties start with a lowercase letter:
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 somer.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
, ...).