jquery ajax表单提交赢得';t绑定MVC4中的复杂模型

jquery ajax表单提交赢得';t绑定MVC4中的复杂模型,jquery,ajax,asp.net-mvc,asp.net-mvc-4,Jquery,Ajax,Asp.net Mvc,Asp.net Mvc 4,我有一个表单,我需要通过ajax提交,它正在提交,但没有绑定到模型 我的jquery源代码如下 function SubmitForm() { console.log($("#PackageSubscription").serialize()); $.ajax({ url: '/HelpDesk/CalculateCost', cache: false, processData: false, data: $("#PackageSubscription").ser

我有一个表单,我需要通过ajax提交,它正在提交,但没有绑定到模型

我的jquery源代码如下

function SubmitForm() {
console.log($("#PackageSubscription").serialize());
$.ajax({
    url: '/HelpDesk/CalculateCost',
    cache: false,
    processData: false,
    data: $("#PackageSubscription").serialize(),
    type: 'POST',
    success: function (data) {
    }
});
}

当我通过submit按钮使用标准mvc submit(同步)时,完全相同的表单绑定

有趣的是,控制台日志包含所有表单值,当我们同步提交表单时,它们完全相同(来自ajax调用的控制台日志字符串和来自fiddler请求检查器的表单值完全相同)

一些示例数据如下

MemberId=12345678
&SitePackges[0].SiteId=50
&SitePackges[0].SizeIndicator=2
&SitePackges[0].LstPackageDisplayItems[0].PackageId=4
&SitePackges[0].LstPackageDisplayItems[0].Name=PAT and Emergency Lighting 
&SitePackges[0].LstPackageDisplayItems[0].IsSubscribed=True
&SitePackges[0].LstPackageDisplayItems[0].LastServiceDate=
&SitePackges[0].LstPackageDisplayItems[0].ProposedDate=
&SitePackges[0].LstPackageDisplayItems[1].PackageId=6
&SitePackges[0].LstPackageDisplayItems[1].Name=Fire Alarm and Extinguishers
&SitePackges[0].LstPackageDisplayItems[1].IsSubscribed=True
&SitePackges[0].LstPackageDisplayItems[1].LastServiceDate=
&SitePackges[0].LstPackageDisplayItems[1].ProposedDate=
我的viewmodel看起来像

public class PpmTypePackageSubscriptionModel
{        
    public int MemberId { get; set; }
    public DateTime TimeStamp { get; set; }
    public List<SitePackage> SitePackges { get; set; }
    public double TotalCost { get; set; }

    public PpmTypePackageSubscriptionModel()
    {
        SitePackges=new List<SitePackage>();
    }
}

public class SitePackage
{
    public int SiteId { get; set; }
    public int SizeIndicator { get; set; } 
    public string Site { get; set; }

    public List<PackageDisplayItem> LstPackageDisplayItems { get; set; }

    public SitePackage()
    {
        LstPackageDisplayItems=new List<PackageDisplayItem>();

    }

}

如果我理解正确,表单不会更新,因为您没有对从ajax响应接收到的数据进行任何处理

您应该将结果绑定到ajax success函数中。Ajax是异步的,因此数据是发布的,但响应不一定是立即的。当成功接收到响应(没有超时或连接丢失等)时,ajax调用转到success函数,并且响应数据存储在变量“data”中

尝试执行以下操作:

function SubmitForm() {
console.log($("#PackageSubscription").serialize());
$.ajax({
    url: '/HelpDesk/CalculateCost',
    cache: false,
    processData: false,
    data: $("#PackageSubscription").serialize(),
    type: 'POST',
    success: function (data) {
        alert(data); // This will only show the response for you, use for debugging only
        $("#MemberId").value(data.MemberId);
    }
});

从ajax中删除processData:false。那么它肯定会与您的模型绑定。请阅读以下内容:

processData(默认值:true) 类型:布尔型
默认情况下,作为对象传递到数据选项的数据(从技术上讲,是字符串以外的任何内容)将被处理并转换为查询字符串,符合默认内容类型“application/x-www-form-urlencoded”。如果要发送DOMDocument或其他未处理的数据,请将此选项设置为false。

这可能是serialize()函数的问题

尝试改用JSON.stringify

<script type="text/javascript">
function OnBtnSubmitClick(s, e) {
    var item1 = SecurityCode.GetText();
    var item2 = SecurityCoderMnem.GetText();
    var item3 = SecurityRegNum.GetText();
    var item4 = SecurityIsin.GetText();
    var item5 = document.getElementById("DocOrderSecurityOut_Id").value;
    var item6 = document.getElementById("IsEdit").value;

    var jsmodel = {
        DocOrderSecurityOut: {
            SecurityCode: item1,
            SecurityCoderMnem: item2,
            SecurityRegNum: item3,
            SecurityIsin: item4,
            Id: item5
        },
        IsEdit: item6
    };

    $.ajax({
        url: '@Url.Action("AjaxForm", "DocOrderSecurityOut")',
        data: JSON.stringify(jsmodel),
        dataType: 'html',
        contentType: "application/json; charset=utf-8",
        type: "POST",
        beforeSend: function () { loadingPanel.Show(); },
        complete: function () { loadingPanel.Hide(); },
        error: function (x, status, error) {
            alert("Error code: " + x.status + '\n' +
                "State: " + status + ". More info: " + error);
        },
        success: function (response) {
            $("#container").html(response);
        }
    });
}
在Global.asax中:

        ValueProviderFactories.Factories.Add(
            new JsonValueProviderFactory());

请尝试从构造函数中删除
SitePackages
初始化。很抱歉,这没有任何区别。请使用
[FromBody]
装饰控制器操作中的参数,如“public ActionResult ActionName([FromBody]PpmTypePackageSubscriptionModel value)@StephenMuecke谢谢。我希望它也能很好地工作,但我不明白它为什么会失败。是的,我已经重命名了模型,这不是问题。这可能是数据相关的问题吗?我的意思是,mvc模型绑定器在通过ajax发出请求时不会忽略某些字符或数据。正是因为这个原因,我添加了
processData:false
,我将删除它,并且我确信在我添加该属性之前问题就已经存在。应该不会有任何区别(您甚至已经使用fiddler自己确认了)。如果您注释掉脚本并进行正常的提交,那么ajax提交也应该正常工作。@Rohit Arora已经尝试过了,没有什么区别
function SubmitForm() {
console.log($("#PackageSubscription").serialize());
$.ajax({
    url: '/HelpDesk/CalculateCost',
    cache: false,
    processData: false,
    data: $("#PackageSubscription").serialize(),
    type: 'POST',
    success: function (data) {
        alert(data); // This will only show the response for you, use for debugging only
        $("#MemberId").value(data.MemberId);
    }
});
<script type="text/javascript">
function OnBtnSubmitClick(s, e) {
    var item1 = SecurityCode.GetText();
    var item2 = SecurityCoderMnem.GetText();
    var item3 = SecurityRegNum.GetText();
    var item4 = SecurityIsin.GetText();
    var item5 = document.getElementById("DocOrderSecurityOut_Id").value;
    var item6 = document.getElementById("IsEdit").value;

    var jsmodel = {
        DocOrderSecurityOut: {
            SecurityCode: item1,
            SecurityCoderMnem: item2,
            SecurityRegNum: item3,
            SecurityIsin: item4,
            Id: item5
        },
        IsEdit: item6
    };

    $.ajax({
        url: '@Url.Action("AjaxForm", "DocOrderSecurityOut")',
        data: JSON.stringify(jsmodel),
        dataType: 'html',
        contentType: "application/json; charset=utf-8",
        type: "POST",
        beforeSend: function () { loadingPanel.Show(); },
        complete: function () { loadingPanel.Hide(); },
        error: function (x, status, error) {
            alert("Error code: " + x.status + '\n' +
                "State: " + status + ". More info: " + error);
        },
        success: function (response) {
            $("#container").html(response);
        }
    });
}
[HttpPost]
    public ActionResult AjaxForm(DocOrderSecurityOutViewModel model)
    {
        // magic
    }
        ValueProviderFactories.Factories.Add(
            new JsonValueProviderFactory());