一尘不染

通过AJAX请求无法进行MVC模型绑定

ajax

通过AJAX进行MVC模型绑定时遇到一些麻烦。

谁能告诉我为什么CreateTransfereeDetails属性没有绑定,它总是返回为“ null”。

模型:

public class ResolveProfileSelectionRequiredModel
{
    public CreateTransfereeModel CreateTransfereeDetails { get; set; }

    public bool NewTransfereeSelected { get; set; }
}

public class CreateTransfereeModel
{
    [Display(Name = "Transferee Name:")]
    public string TransfereeName { get; set; }
}

HTML:

<input type="text" id="TransfereeName" />
<input type="hidden" id="NewTrasnfereeSelected" />

JavaScript:

var createTransfereeDetails =
{
    "TransfereeName": $("#TransfereeName").val()
};

$.ajax({
    url: "/myurl",
    dataType: "json",
    traditional: true,
    type: "POST",
    data: {
        CreateTransfereeDetails: createTransfereeDetails,
        NewTransfereeSelected: $("#NewTransfereeSelected").val()
    },
    success: function (result) {
        //
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        //
    },
    complete: function () {
        //
    }
});

谢谢!


阅读 340

收藏
2020-07-26

共1个答案

一尘不染

用于name attribute表单内的输入字段。Name attribute's values自动分配给模型的属性。

<form method="post" id="frm">
<input type="text" name="id="TransfereeName" " id="TransfereeName" />
<input type="hidden" name="NewTrasnfereeSelected"  id="NewTrasnfereeSelected" />
<input type="button" onclick="submit()" value="submit" />
</form>

并使用jquery的serialize()函数使用ajax传递数据

function submit(){
    $.ajax({
        url: "/myurl",
        dataType: "json",
        traditional: true,
        type: "POST",
        data: $('#frm').serialize(),
        success: function (result) {
            //
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //
        },
        complete: function () {
            //
        }
    });
}
2020-07-26