【问题标题】:form.serialise is returning null to controllerform.serialise 将 null 返回给控制器
【发布时间】:2020-01-08 20:50:44
【问题描述】:

我是一名新程序员,我正在尝试使用 ajax 在数据库中添加一行,方法是使用 form.serialise 发送新行。我发送的模型新行是用于创建视图的主模型的部分

我知道遍历每一列以匹配数据库中表的列是一种繁琐的方法,但是,我想使用更简单的选项——使用 ajax。

这是我用来创建视图的模型的一部分:

    public List <Appliance> Appliances { get; set; }


    public Appliance NewAppliance { get; set; }
    public string DepositTotalBalance { get; set; }

    public string DepositGiven { get; set; }
    public string DepositReturned { get; set; }

这是我的控制器方法:

              public ActionResult CreateCheck(Appliance NewAppliance)
    {
            db.Appliances.InsertOnSubmit(app);
        db.SubmitChanges();

        var appIndb = (from a in db.Appliances
                             where a.ApartmentID == app.ApartmentID
                             select a).LastOrDefault();

              var applianceNew= appRepo.Add(appIndb );
                  return Json(new { success = true, appliance = 
             applianceNew}, 
                     JsonRequestBehavior.AllowGet);
                      }

这是我的观点 - 我在表单中的字段是 ALL html.editorfor 或 hiddenfor- 我没有指定 任何一个的名字 他们:

                     <form id="hidden-form-appliance">
                @Html.AntiForgeryToken()

                <div class="form-horizontal">


                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })


                    <br />

                    <div class="flex-container">
                        <div class="flex-container flex-vericalDirection">
                            <p class="removeMargin">Appliance Name </p>
                            @*@Html.LabelFor(model => model.NewAppliance.ApplianceName, htmlAttributes: new { @class = "control-label col-md-2" })*@
                            <div class="inputModal" id="applianceNameDiv">
                                @Html.EditorFor(model => model.NewAppliance.ApplianceName, new { htmlAttributes = new { @class = "form-control", id = "applianceName" } })
                                @Html.ValidationMessageFor(model => model.NewAppliance.ApplianceName, "", new { @class = "text-danger" })
                            </div>
                        </div>


                        <div class="flex-container flex-vericalDirection">
                            <p class="removeMargin"> Unit</p>
                            <div class="inputModal">
                                @{ var unitsList = new List<SelectListItem>();


                                    foreach (var item in Model.AllApartmentsForID)
                                    {
                                        var unitType = new SelectListItem();
                                        unitType.Value = item.ApartmentID.ToString();
                                        unitType.Text = item.ApartmentNumber;


                                        unitsList.Add(unitType);
                                    }
                                }
                                @Html.DropDownListFor(model => model.NewAppliance.ApartmentID, unitsList, "Select Unit", new { @class = "form-control", @id = "ap_ApartmentID" })
                                @Html.ValidationMessageFor(model => model.NewAppliance.ApartmentID, "", new { @class = "text-danger" })


                            </div>
                        </div>






                    </div>



                    <div class="flex-container">

                        <div class="flex-container flex-vericalDirection">
                            <p class="removeMargin"> Make</p>
                            <div class="inputModal">
                                @Html.EditorFor(model => model.NewAppliance.Make, new { htmlAttributes = new { @class = "form-control", id = "editedDistrict" } })
                                @Html.ValidationMessageFor(model => model.NewAppliance.Make, "", new { @class = "text-danger" })
                            </div>
                        </div>

                        <div class="flex-container flex-vericalDirection">
                            <p class="removeMargin"> Model</p>
                            <div class="inputModal">
                                @Html.EditorFor(model => model.NewAppliance.Model, new { htmlAttributes = new { @class = "form-control", id = "editedDistrict" } })
                                @Html.ValidationMessageFor(model => model.NewAppliance.Model, "", new { @class = "text-danger" })
                            </div>
                        </div>

                    </div>



                    <div class="flex-container flex-vericalDirection removeMargin">
                        <p class="removeMargin">Description</p>

                        <textarea class="text-area-input-form">
                        @Model.NewAppliance.DescriptionDetails

                    </textarea>
                    </div>


                    <div class="flex-container">


                        <div class="flex-container flex-vericalDirection">
                            <p class="removeMargin"> Store</p>
                            <div class="inputModal">
                                @Html.EditorFor(model => model.NewAppliance.Store, new { htmlAttributes = new { @class = "form-control", id = "editedAddress" } })
                                @Html.ValidationMessageFor(model => model.NewAppliance.Store, "", new { @class = "text-danger" })
                            </div>
                        </div>

                        <div class="flex-container flex-vericalDirection">
                            <p class="removeMargin"> Cost</p>
                            <div class="inputModal">
                                @Html.EditorFor(model => model.NewAppliance.Cost, new { htmlAttributes = new { @class = "form-control", id = "editedAddress" } })
                                @Html.ValidationMessageFor(model => model.NewAppliance.Cost, "", new { @class = "text-danger" })
                            </div>
                        </div>
                    </div>


                    <div class="flex-container flex-vericalDirection">
                        <p class="removeMargin"> Installed On</p>
                        <div class="inputModal">
                            @Html.EditorFor(model => model.NewAppliance.DateOfInstallment, new { htmlAttributes = new { @class = "form-control", id = "datepicker" } })
                            @Html.ValidationMessageFor(model => model.NewAppliance.DateOfInstallment, "", new { @class = "text-danger" })
                        </div>
                    </div>


                </div>
                </form>

这是js:

                                  $('.btn.btn-- 
                         primary.saveNewAppliance').on('click', 
                               function () {

            alert($('#hidden-form-appliance').serialize());

            $.ajax({

                url: '@Url.Action("CreateCheck", "Appliance")',
                data:{ NewAppliance: $('#hidden-form- 
                 appliance').serialize()},
              success: function(data) {
        if (data) {  // check if data is defined
           if (data.success) { // if success is true
               alert("It Worked!"); 

               }
             }
          }
         }); 

更新:这是源代码:

            <form id="hidden-form-appliance">
                <input name="__RequestVerificationToken" type="hidden" 
             value="MLW1wQJnd0WnHyzEaOJO6kAEVm-r_9YYhDliWfy28Qxs6- 
                 Q6kabsK48RICT5uAIhtJ1WQ3Hrq6S-axQwIoMw5F32t6webLXW- 
                     T7npEad1lkn-7dVDO6HFyGcXsJpv2ayhiithucgvg3Ro2kd8Pk5MQ2" 
                         />

                               <input class="form-control text-box single- 
                            line" id="applianceName" 
                        name="NewAppliance.ApplianceName" 
                          type="text" value="" />



                                <select class="form-control" data- 
                           val="true" data-val-number="The field 
                            ApartmentID must be a number." 
                             id="ap_ApartmentID" 
                           name="NewAppliance.ApartmentID"><option 
                       value="">Select Unit</option>
                            </select>


                                <input class="form-control text-box single- 
                          line" id="editedDistrict" 
                               name="NewAppliance.Make" type="text" 
                value="" />

                                <input class="form-control text-box single- 
                            line" id="editedDistrict" 
                               name="NewAppliance.Model" type="text" 
                                           value="" />






                    <div class="flex-container flex-vericalDirection 
                            removeMargin">
                        <p class="removeMargin">Description</p>

                        <textarea class="text-area-input-form">


                    </textarea>



                                <input class="form-control text-box single- 
                               line" id="editedAddress" 
                           name="NewAppliance.Store" type="text" value="" 
                                  />



                                <input class="form-control text-box single- 
                                       line" data-val="true" data-val- 
                                   number="The field Cost must be a 
                                   number." id="editedAddress" 
                               name="NewAppliance.Cost" type="text" 
                           value="" />






                            <input class="form-control text-box single- 
                     line" data-val="true" data-val-date="The field 
                     DateOfInstallment must be a date." data-val- 
                         required="The DateOfInstallment field is 
                         required." id="datepicker" 
                     name="NewAppliance.DateOfInstallment" type="date" 
                       value="" />



            </form>

我收到错误“值不能为空”。 (设备型号作为 null 发送)。

更新 2:

console.log($('#hidden-form-appliance').serialize()) 产量:

Appliance.ApplianceName=jhbk&Appliance.ApartmentID=1388&Appliance.ApplianceID=0&Appliance.Make=hhj&Appliance.Model=hku&Appliance.DescriptionDetails=bhjk&Appliance.Store=gjh&Appliance.Cost=789&Appliance.DateOfInstallment=09%2F08%2F2009

有人可以帮忙吗?谢谢

【问题讨论】:

  • 您能否编辑您的问题并向我们提供有关生成的 HTML 在您的表单中的外观的更多信息?那里的字段是否具有指定的名称属性值?
  • 请参阅上面的编辑 - 我现在附上了完整的表格
  • 谢谢,Jane,但这不是生成的 HTML。它是标记。您生成的 HTML 就是在浏览器中显示的内容。您可以使用查看源代码查看。请将生成的 HTML 也复制到您的问题中。
  • @Lajos Arpad 请查看更新谢谢
  • 表单的 id 为 buildingForm,而您的代码搜索 id 为 hidden-form-appliance 的表单。这似乎是问题所在。什么是 console.log($('#buildingForm').serialize());产量?

标签: jquery asp.net json asp.net-mvc-5


【解决方案1】:

我没有为他们指定名字

您似乎指定了编辑器的 id 属性,例如:

@Html.EditorFor(model => model.NewAppliance.Cost, new { htmlAttributes = new { @class = "form-control", id = "editedAddress" } })

可能会影响生成的请求数据对的因素。由于您使用强类型编辑器,请尽量不要显式指定此 html 属性。如果您需要在 js/css 中操作它们,请尝试操作 css 类。

【讨论】:

  • 我认为这是添加css类的方法,你能给我一个如何添加css类的例子
  • 在序列化或提交表单数据时不使用表单字段的ID属性,而是使用名称
猜你喜欢
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多