【问题标题】:checkboxfor bind to model ajax postback用于绑定到模型 ajax 回发的复选框
【发布时间】:2014-12-17 20:01:36
【问题描述】:

我正在尝试通过控制器中的 ajax 回发获取复选框的选中值,但即使在单击按钮控件之前在视图中选中了复选框,它也会给我错误。

我的代码如下所示:

[HttpPost]
public ActionResult CivilSurveys(CivilSurveyViewModel modelData)
{
  try
  {
    var s = Request["SurveyAccepted"].Contains("true");
    if (modelData.SurveyAccepted)
      {
        modelData.SurveyAcceptedBy = int.Parse(Session["SessionUserId"].ToString());
        modelData.SiteDiagram = ViewBag.Image;
        modelData = (BAL.Surveys.GetCivilSurvey(modelData));
      }
      return View(modelData);
    }
    catch (Exception ex)
    {
      Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
      return View();
    }
  }

查看

@using (Html.BeginForm("", "", FormMethod.Post, new { id = "frmCivilSurveys" }))
{
  <div class="ControlSet">
    @Html.LabelFor(model => model.SurveyAcceptedBy):
    @Html.CheckBoxFor(model => model.SurveyAccepted, new { style = "margin-left:198px;"     })
  </div>
  <div style="clear: both; margin: 10px; padding-top: 10px; overflow: hidden;">
    <input type="submit" class="k-button" value="Create" style="float: right;" id="btnCreateCivilSurvey" />
    <input type="button" class="k-button" value="Update" id="btnEditCivilSurvey" style="float: right;" />
  </div>

<script>
  $("#btnCreateCivilSurvey").click(function() {
    if ($("#frmCivilSurveys").valid()) {
      $.ajax({
        type: "POST",
        url: "@Url.Action("CivilSurveys", "Civils")",
        data: JSON.stringify($('#frmCivilSurveys').serializeObject()),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        async: true,
        cache: false,
        success: function (msg) {
          if (msg.status == "1") {       }
            alert(msg.message);
          }
        });
      } else {
        $($("#frmCivilSurveys").validate().errorList[0].element).focus();
      }
      return false;
  });
</script>

这是因为使用 checkboxfor 时自动创建的隐藏字段。

我已经解决了这个问题,方法是使用复选框类型的输入并在 foreach 循环中为它们手动设置 ID,如下所示:

@foreach (var item in Model.SurveyTypeList)
{
  @Html.Label(item.Text)
  <input name="SurveyTypeList[@i].Text" type="hidden" value="@item.Text" />
  <input name="SurveyTypeList[@i].Value" type="hidden" value="@item.Value" />
 <input data-val="true" id="SurveyTypeList@(i)__IsSelected" name="SurveyTypeList[@i].IsSelected"          style="margin-right: 200px; float: right" type="checkbox" value="true" />
  <br /><br />
  i++;
  }

但这不是一个完美的解决方案,我需要一些更完美的解决方案

【问题讨论】:

  • Whats .serializeObject() 你在使用插件吗?如果你只使用.serialize() 会发生什么
  • 我假设它是hongymagic jQuery.serializeObject,在这种情况下可能是问题所在 - 它将复选框的值及其关联的隐藏输入转换为一个无法绑定到boolean 的数组。
  • 你试过我的答案了吗?有用吗?

标签: c# jquery asp.net-mvc


【解决方案1】:

把你的ajax调用改成

$.ajax({
    type: "POST",
    url: "@Url.Action("CivilSurveys", "Civils")",
    data: $('#frmCivilSurveys')),
    // dataType: "json", - Note you appear to be returning a view so this should be html
    cache: false,
    success: function (msg) {
      ....

关键点

  1. 使用.serialize(),而不是serializObject()
  2. 不要使用JSON.stringify
  3. 删除contentType: "application/json; charset=utf-8"

【讨论】:

    【解决方案2】:

    这是因为使用 checkboxfor 时自动创建的隐藏字段。

    我已经解决了这个问题,方法是使用复选框类型的输入并在 foreach 循环中为它们手动设置 ID,如下所示:

     @foreach (var item in Model.SurveyTypeList)
     {
      @Html.Label(item.Text)
      <input name="SurveyTypeList[@i].Text" type="hidden" value="@item.Text" />
       <input name="SurveyTypeList[@i].Value" type="hidden" value="@item.Value" />
      <input data-val="true" id="SurveyTypeList@(i)__IsSelected" name="SurveyTypeList[@i].IsSelected"      style="margin-right: 200px; float: right" type="checkbox" value="true" />
     <br /><br />
      i++;
      }
    

    但这不是一个完美的解决方案,我需要一些更完美的解决方案

    【讨论】:

    • 这不是必需的,而且是呈现 html 的糟糕方式:)。请参考我的回答,您的 ajax 参数中有许多不正确的参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 2014-08-18
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 2015-12-22
    • 2014-05-15
    相关资源
    最近更新 更多