jQuery的Ajax表单提交不会绑定在MVC 4一个复杂的模型 [英] jquery ajax form submit won't bind a complex model in mvc 4

查看:108
本文介绍了jQuery的Ajax表单提交不会绑定在MVC 4一个复杂的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要通过AJAX是提交,但不具约束力的模型提交表单。

我的jQuery的源$ C ​​$ c是如下

 函数SubmitForm(){
的console.log($(#PackageSubscription)序列化());
$阿贾克斯({
    网址:'/帮助台/ CalculateCost',
    缓存:假的,
    过程数据:假的,
    数据:$(#PackageSubscription)序列化()。
    键入:POST,
    成功:功能(数据){
    }
});
 

}

当我用的是标准的MVC提交(同步)通过提交按钮同样的形式并结合。

有趣的是控制台日志具有所有形式的价值观和他们是完全一样的,当我们提交表单同步(从Ajax调用和表格值控制台登录串由小提琴手要求检查是完全一样的)

一些示例数据就像

 会员id = 12345678
&安培; SitePackges [0] .SiteId = 50
&安培; SitePackges [0] .SizeIndicator = 2
&安培; SitePackges [0] .LstPackageDisplayItems [0] .PackageId = 4
&放大器; SitePackges [0] .LstPackageDisplayItems [0] .Name点= PAT和应急照明
&放大器; 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点=火警和灭火器
&放大器; SitePackges [0] .LstPackageDisplayItems [1] .IsSubscribed =真
&安培; SitePackges [0] .LstPackageDisplayItems [1] .LastServiceDate =
&安培; SitePackges [0] .LstPackageDisplayItems [1] .ProposedDate =
 

和我的视图模型看起来像

 公共类PpmTypePackageSubscriptionModel
{
    公众诠释会员id {获得;组; }
    公共DateTime时间戳{获得;组; }
    公开名单< SitePackage> SitePackges {获得;组; }
    公共双TotalCost {获得;组; }

    公共PpmTypePackageSubscriptionModel()
    {
        SitePackges =新的名单,其中,SitePackage>();
    }
}

公共类SitePackage
{
    公众诠释SITEID {获得;组; }
    公众诠释SizeIndicator {获得;组; }
    公共字符串网站{获得;组; }

    公开名单< PackageDisplayItem> LstPackageDisplayItems {获得;组; }

    公共SitePackage()
    {
        LstPackageDisplayItems =新的名单,其中,PackageDisplayItem>();

    }

}
 

请参阅下面查看的标记了

  @using Booker.WebUI.Models
@model PpmTypePackageSubscriptionModel
@using(@ Html.BeginForm(CalculateCost,服务台,FormMethod.Post,新{@class =形,ID =PackageSubscription,名字=PackageSubscription}))
{
@ Html.AntiForgeryToken()
@ Html.HiddenFor(X => x.MemberId)
<表类=桌桌响应表凝聚表悬停表条纹>
    @for(INT I = 0; I< Model.SitePackges.Count;我++)
    {
        &其中; TR>
            < TD类=siteHeading>
                @ Html.HiddenFor(X => x.SitePackges [I] .SiteId)@ Html.DisplayFor(X => x.SitePackges [I] .Site)
                @ Html.HiddenFor(X => x.SitePackges [I] .SizeIndicator)@ Html.DisplayFor(X => x.SitePackges [I] .SizeIndicator)
            < / TD>
        < / TR>
        &其中; TR>
            百分位类=COL-SM-3>
                名称
            < /第i个
            百分位类=COL-SM-2>
                订阅
            < /第i个
            百分位类=COL-SM-2>
                最后服务日期如果知道的话
            < /第i个
            百分位类=COL-SM-2>
                拟批准日期
            < /第i个
        < / TR>

        对于(INT J = 0; J< Model.SitePackges [I] .LstPackageDisplayItems.Count; J ++)
        {
            &其中; TR>
                < TD>
                    @ Html.HiddenFor(X => x.SitePackges [I] .LstPackageDisplayItems [J] .PackageId)
                    @ Html.HiddenFor(X => x.SitePackges [I] .LstPackageDisplayItems [J] .Name点)
                    @ Html.DisplayFor(X => x.SitePackges [I] .LstPackageDisplayItems [J] .Name点)
                < / TD>
                < TD>
                    @ Html.RadioButtonFor(X => x.SitePackges [I] .LstPackageDisplayItems [J]。.IsSubscribed,真,新{@class =拉左})<标签类=拉左>是&放; NBSP;&安培; NBSP;< /标签>
                    @ Html.RadioButtonFor(X => x.SitePackges [I] .LstPackageDisplayItems [J]。.IsSubscribed,假的,新的{@class =拉左})<标签类=拉左>无&LT ; /标签>
                < / TD>
                < TD>
                    @ Html.TextBoxFor(X => x.SitePackges [I] .LstPackageDisplayItems [J] .LastServiceDate,{0:D MMM YYYY},新{@class =jquery_datepicker形式的控制,自动完成=关闭 })
                < / TD>
                < TD>
                    @ Html.TextBoxFor(X => x.SitePackges [I] .LstPackageDisplayItems [J] .ProposedDate,{0:D MMM YYYY},新{@class =jquery_datepicker形式的控制,自动完成=关闭 })
                < / TD>
            < / TR>
        }

    }
< /表>

< D​​IV CLASS =行>
  < D​​IV CLASS =COL-SM-3>< P>停车可用性和LT; / P>< / DIV>
    < D​​IV CLASS =COL-SM-5>
        <选择一个id =ParkingAvailability级=表单控制NAME =ParkingAvailability>
            <期权价值=1>免费停车场< /选项>
            <期权价值=2>付费停车场和LT; /选项>
        < /选择>
    < / DIV>
< / DIV>
< D​​IV CLASS =行>
    < D​​IV CLASS =COL-SM-3>< P>访问时间< / P>< / DIV>< D​​IV CLASS =COL-SM-5> <输入类=表单控制NAME =SiteContactEmail值=0900-1500 MonSat>
< / DIV
 < / DIV>
< D​​IV CLASS =行>
    < D​​IV CLASS =COL-SM-3>
        <输入类=BTN BTN-主@ *类型=提交* @的onclick =SubmitForm();返回false;值=计算成本/>
    < / DIV>
    < D​​IV CLASS =COL-SM-5>
        <跨度ID =totalCost级=隐藏的形式控制>< / SPAN>
    < / DIV>
< / DIV>

< D​​IV CLASS =行>
    < D​​IV CLASS =COL-SM-5 COL-SM-偏移3>
        <输入类=BTN BTN-成功类型=提交值=报批/>
        <输入类=BTN BTN-危险类型=提交值=取消注册/>
    < / DIV>
< / DIV>
 

}

我的主要观点有以下标志了

 < D​​IV ID =标签>
        < UL>
            <李>< A HREF =#标签-1>会员网站< / A>< /李>
            <李>< A HREF =#标签-2>服务和包< / A>< /李>

        < / UL>
        < D​​IV ID =标签-1>
            @ Html.Partial(_ MemberSites)
        < / DIV>
        < D​​IV ID =标签-2>
            @ Html.Action(GetAllPpmTypePackages,新{@id = @ M​​odel.MemberNumber})
        < / DIV>

< / DIV>
 

和我的操作方法是这样的

  [HTTPGET]
    公众的ActionResult GetAllPpmTypePackages(INT ID)
    {
      //处理创建视图模型,并通过查看
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    公众的ActionResult CalculateCost(PpmTypePackageSubscriptionModel ppmTypePackageSubscriptionModel)
    {
    //处理
    }
 

解决方案

这可能是序列化()函数的一个问题。

尽量使用JSON.stringify来代替。

 <脚本类型=文/ JavaScript的>
功能OnBtnSubmitClick(S,E){
    VAR ITEM1 =安全code.GetText();
    VAR项目2 =安全coderMnem.GetText();
    VAR项目3 = SecurityRegNum.GetText();
    变种ITEM4 = SecurityIsin.GetText();
    VAR item5 =的document.getElementById(DocOrderSecurityOut_Id)值。
    VAR item6 =的document.getElementById(IsEdit)值。

    VAR jsmodel = {
        DocOrderSecurityOut:{
            安全code:项目1,
            安全coderMnem:项目2,
            SecurityRegNum:项目3,
            SecurityIsin:ITEM4,
            编号:item5
        },
        IsEdit:item6
    };

    $阿贾克斯({
        网址:@ Url.Action(当作ajaxForm,DocOrderSecurityOut),
        数据:JSON.stringify(jsmodel)
        数据类型:HTML,
        的contentType:应用/ JSON的;字符集= UTF-8,
        键入:POST,
        beforeSend:功能(){loadingPanel.Show(); },
        完成:函数(){loadingPanel.Hide(); },
        错误:函数(X,状态,错误){
            警报(错误code:+ x.status +'\ N'+
                状态:+状态+。更多信息:+误差);
        },
        成功:函数(响应){
            $(#集装箱)HTML(响应);
        }
    });
}
 

控制器:

  [HttpPost]
    公众的ActionResult当作ajaxForm(DocOrderSecurityOutViewModel模型)
    {
        // 魔法
    }
 

在Global.asax中:

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

I have a form which I need to submit via ajax is submitting but not binding to the model.

My jquery source code is as below

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

}

Exactly the same form does bind when I use the standard mvc submit (synchronous ) via submit button.

Interestingly the console log has all the form values and they are exactly the same when we submit the form synchronously ( Console log string from ajax call and form values from fiddler request inspector are exactly the same)

some example data is like

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=

and my viewmodel looks like

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>();

    }

}

See below the mark up of View

@using Booker.WebUI.Models
@model PpmTypePackageSubscriptionModel
@using (@Html.BeginForm("CalculateCost", "HelpDesk", FormMethod.Post, new { @class = "form", id = "PackageSubscription", name = "PackageSubscription" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(x => x.MemberId)
<table class="table table-responsive table-condensed table-hover table-striped">
    @for (int i = 0; i < Model.SitePackges.Count; i++)
    {
        <tr>
            <td class="siteHeading">
                @Html.HiddenFor(x => x.SitePackges[i].SiteId) @Html.DisplayFor(x => x.SitePackges[i].Site)
                @Html.HiddenFor(x => x.SitePackges[i].SizeIndicator) @Html.DisplayFor(x => x.SitePackges[i].SizeIndicator)
            </td>
        </tr>
        <tr>
            <th class="col-sm-3">
                Name
            </th>
            <th class="col-sm-2">
                Subscribe
            </th>
            <th class="col-sm-2">
                Last Service Date If Known
            </th>
            <th class="col-sm-2">
                Proposed Date
            </th>
        </tr>

        for (int j = 0; j < Model.SitePackges[i].LstPackageDisplayItems.Count; j++)
        {
            <tr>
                <td>
                    @Html.HiddenFor(x => x.SitePackges[i].LstPackageDisplayItems[j].PackageId)
                    @Html.HiddenFor(x => x.SitePackges[i].LstPackageDisplayItems[j].Name)
                    @Html.DisplayFor(x => x.SitePackges[i].LstPackageDisplayItems[j].Name)
                </td>
                <td>
                    @Html.RadioButtonFor(x => x.SitePackges[i].LstPackageDisplayItems[j].IsSubscribed, true, new { @class = "pull-left " })<label class="pull-left">Yes&nbsp;&nbsp;</label>
                    @Html.RadioButtonFor(x => x.SitePackges[i].LstPackageDisplayItems[j].IsSubscribed, false, new { @class = "pull-left" })<label class="pull-left">No</label>
                </td>
                <td>
                    @Html.TextBoxFor(x => x.SitePackges[i].LstPackageDisplayItems[j].LastServiceDate, "{0:d MMM yyyy}", new { @class = "jquery_datepicker form-control", autocomplete = "off" })
                </td>
                <td>
                    @Html.TextBoxFor(x => x.SitePackges[i].LstPackageDisplayItems[j].ProposedDate, "{0:d MMM yyyy}", new { @class = "jquery_datepicker form-control", autocomplete = "off" })
                </td>
            </tr>
        }

    }
</table>

<div class="row">
  <div class="col-sm-3"><p>Parking Availability</p></div>
    <div class="col-sm-5">
        <select id="ParkingAvailability" class="form-control" name="ParkingAvailability">
            <option value="1">Free Carpark</option>
            <option value="2">Paid Carpark</option>
        </select>
    </div>
</div>
<div class="row">
    <div class="col-sm-3"><p>Access Time</p></div><div class="col-sm-5"> <input class="form-control" name="SiteContactEmail" value="0900-1500 MonSat">
</div
 </div>
<div class="row">
    <div class="col-sm-3">
        <input class="btn btn-primary" @*type="submit"*@ onclick="SubmitForm(); return false;" value="Calculate Cost" />
    </div>
    <div class="col-sm-5">
        <span id="totalCost" class="hide form-control"></span>
    </div>
</div>

<div class="row">
    <div class="col-sm-5 col-sm-offset-3">
        <input class="btn btn-success" type="submit" value="Submit For Approval" />
        <input class="btn btn-danger" type="submit" value="Cancel Signup" />
    </div>
</div>

}

My main view has the following mark up

<div id="tabs">
        <ul>
            <li><a href="#tabs-1">Member Sites </a></li>
            <li><a href="#tabs-2">Services and Packages</a></li>

        </ul>
        <div id="tabs-1">
            @Html.Partial("_MemberSites")
        </div>
        <div id="tabs-2">
            @Html.Action("GetAllPpmTypePackages", new { @id = @Model.MemberNumber })
        </div>

</div>

And my action methods looks like this

    [HttpGet]
    public ActionResult GetAllPpmTypePackages(int id)
    {
      // Processing to create the viewmodel and pass to view
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CalculateCost(PpmTypePackageSubscriptionModel ppmTypePackageSubscriptionModel)
    {
    // Processing
    }

解决方案

That might be a problem of serialize() function.

Try to use JSON.stringify instead.

<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);
        }
    });
}

Controller:

[HttpPost]
    public ActionResult AjaxForm(DocOrderSecurityOutViewModel model)
    {
        // magic
    }

In Global.asax:

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

这篇关于jQuery的Ajax表单提交不会绑定在MVC 4一个复杂的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆