ASP.NET MVC模型与serialize绑定

时间:2022-09-18 08:19:41

I'm using serialize and JSON.stringify methods to make an Ajax call to my ASP.NET MVC application. MVC is unable to bind the model.

我正在使用serialize和JSON.stringify方法对我的ASP.NET MVC应用程序进行Ajax调用。 MVC无法绑定模型。

This is my JS code and strongly-typed view:

这是我的JS代码和强类型视图:

<script>
    function saveDetails() {
        jsonObj = $('#rdform').serialize();
        $.ajax({
            method: "POST",
            url: "R/SaveDetail",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: JSON.stringify(jsonObj)
        });
    }
</script>

<form id="rdform">
    <div>
        <div>
            @Html.LabelFor(m => m.LiIdH)
            @Html.TextBoxFor(m => m.LiIdH)
        </div>
        <div>
            @Html.LabelFor(m => m.LiIdR)
            @Html.TextBoxFor(m => m.LiIdR)
        </div>
    </div>
    <input type="button" onclick="saveDetails()" />
</form>

The request's payload looks like this:

请求的有效负载如下所示:

"LiIdH=1&LiIdD=&LiIdR=2"

And this is my Action method:

这是我的Action方法:

public bool SaveDetail(Detail detail)

Have I missed something?

我错过了什么吗?

1 个解决方案

#1


The reason you are running into trouble is because of your use of both serialize and JSON.stringify. form.serialize returns a string value, which when passed to JSON.serialize gets wrapped with an extra pair of quotes. The easiest way for you to invoke your action method would be to remove your call to JSON.stringify and also remove the contentType option of the ajax call and go with the default, as shown below:

您遇到麻烦的原因是您使用了serialize和JSON.stringify。 form.serialize返回一个字符串值,当传递给JSON.serialize时,它会被一对额外的引号括起来。调用操作方法的最简单方法是删除对JSON.stringify的调用,并删除ajax调用的contentType选项并使用默认值,如下所示:

<script>
    function saveDetails() {
        $.ajax({
            method: "POST",
            url: "R/SaveDetail",
            dataType: "json",
            data: $('#rdform').serialize()
        });
    }
</script>

#1


The reason you are running into trouble is because of your use of both serialize and JSON.stringify. form.serialize returns a string value, which when passed to JSON.serialize gets wrapped with an extra pair of quotes. The easiest way for you to invoke your action method would be to remove your call to JSON.stringify and also remove the contentType option of the ajax call and go with the default, as shown below:

您遇到麻烦的原因是您使用了serialize和JSON.stringify。 form.serialize返回一个字符串值,当传递给JSON.serialize时,它会被一对额外的引号括起来。调用操作方法的最简单方法是删除对JSON.stringify的调用,并删除ajax调用的contentType选项并使用默认值,如下所示:

<script>
    function saveDetails() {
        $.ajax({
            method: "POST",
            url: "R/SaveDetail",
            dataType: "json",
            data: $('#rdform').serialize()
        });
    }
</script>