MVC模型绑定不能通过AJAX请求工作

时间:2013-10-01 16:33:36

标签: javascript ajax json asp.net-mvc-3 model-binding

通过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 () {
        //
    }
});

谢谢!

1 个答案:

答案 0 :(得分:2)

在表单内的输入字段上使用name attributeName 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 () {
            //
        }
    });
}