编程语言
首页 > 编程语言> > javascript-MVC模型绑定无法通过AJAX请求工作

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

谢谢!

解决方法:

在表单内的输入字段上使用名称属性.名称属性的值会自动分配给模型的属性.

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

标签:javascript,json,ajax,asp-net-mvc-3,model-binding
来源: https://codeday.me/bug/20191012/1899943.html