MVC4无法从AJAX POST将对象属性映射到JSON

时间:2020-11-29 20:14:19

Model:

模型:

public class JsonRequest
{
    public string Data { get; set; }
}

Action:

行动:

[HttpPost]
    public ActionResult Index(JsonRequest data)
    {
        return new JsonResult()
        {
            Data = string.Format("Data: {0}", data.Data), // data.Data == null here
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }

AJAX:

AJAX:

$.ajax({
        type: 'POST',
        url: '@Url.Action("Index", "Home")',
        cache: false,
        data: JSON.stringify({ data: "Hello World!" }),
        success: function(data) {
            alert(data);
        }
    });

JsonRequest object has an instance in Index action but it's Data property was not mapped to the passed JSON. How can I achieve this?

JsonRequest对象在索引操作中有一个实例,但是它的数据属性没有映射到传递的JSON。我如何做到这一点?

2 个解决方案

#1


2  

You need to remove JSON.stringify() call, because jQuery do it itself. And according standarts it's better to write {"Data" : "Hello world"} ("Data" in quotes).

您需要删除JSON.stringify()调用,因为jQuery自己执行它。根据standarts的观点,最好写{"Data": "Hello world"} ("Data" in quotes)。

#2


0  

Well you are specifying data not Data when passing the object back up to the server. This may be the root of the problem. Also specify the contentType in your AJAX request.

当你将对象传回服务器时,你指定的是数据而不是数据。这可能是问题的根源。还要在AJAX请求中指定内容类型。

$.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '@Url.Action("Index", "Home")',
        cache: false,
        data: JSON.stringify({ Data: "Hello World!" }),
        success: function(data) {
            alert(data);
        }
    });

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/

#1


2  

You need to remove JSON.stringify() call, because jQuery do it itself. And according standarts it's better to write {"Data" : "Hello world"} ("Data" in quotes).

您需要删除JSON.stringify()调用,因为jQuery自己执行它。根据standarts的观点,最好写{"Data": "Hello world"} ("Data" in quotes)。

#2


0  

Well you are specifying data not Data when passing the object back up to the server. This may be the root of the problem. Also specify the contentType in your AJAX request.

当你将对象传回服务器时,你指定的是数据而不是数据。这可能是问题的根源。还要在AJAX请求中指定内容类型。

$.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '@Url.Action("Index", "Home")',
        cache: false,
        data: JSON.stringify({ Data: "Hello World!" }),
        success: function(data) {
            alert(data);
        }
    });

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/