MVC Model Binding Not Working via AJAX request

微笑、不失礼 提交于 2019-12-02 07:20:29

问题


Having a little trouble with MVC model binding via AJAX.

Can someone tell me why the CreateTransfereeDetails property is not binding, it always comes back as 'null'.

Model:

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

Thanks!


回答1:


use name attribute on input fields inside form. Name attribute's valuesare automatically assigned to model's properties.

<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>

and use serialize() function of jquery to pass data using 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 () {
            //
        }
    });
}


来源:https://stackoverflow.com/questions/19121458/mvc-model-binding-not-working-via-ajax-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!