【问题标题】:MVC Model Binding List of objectsMVC模型绑定对象列表
【发布时间】:2013-11-25 17:53:32
【问题描述】:

我无法绑定包含对象列表的模型。当我尝试将数据从控制器传递到视图时没有问题,但是当我想将数据发回时,我收到一条消息,该方法不存在。

我正在使用 ajax 调用并将 $form.serialize() 作为数据,并且可以在 fiddler 中看到包含所有数据的列表,但我没有运气绑定。

模型是:

public class Single
{
   public int Id {get;set;}
   public string Name {get;set;}
   public List<SimpleDropdown> dddl {get;set;}
   public int SelectedEmp {get;set;}
}
public class MainModel
{
   public List<Single> main_model_list {get;set;}
}

在我的控制器中,目前的方法是:

[HttpPost]
public string SaveModel(MainModel model)
{
   return "";
}

这个方法不会被调用,但是当我删除参数时调用工作。所以我确定绑定不起作用。我有一个更复杂的模型,但我尽可能地简化了它,但仍然无法让它工作。

所以我的问题是我如何测试它以查看问题所在?

编辑:

我目前没有代码,但该代码是有效的,因为我在项目的其他地方使用它。是这样的:

$("#form").submit(function( ) {
      $.ajax({
        url: "/Controller/SaveModel",
        type: "POST",
        data: $(this).serialize()
    });
});

表单看起来像这样:

@using (Html.BeginForm("SaveModel", "Home", FormMethod.Post, new { id = "form" })) 
{
    @for (var z = 0; z < ViewBag.groupes.Length; z++)
    {
        <div style="border-left: 1px solid black">
            <h1>@ViewBag.groupes[z]</h1>
        </div>
    }
    @for (var i = 0; i < Model.main_model_list.Count; i++)
    {
        <div>@Html.LabelFor(x => x.main_model_list[i].Id)</div>
        <div>@Html.LabelFor(x => x.main_model_list[i].Name)</div>
        <div style="float: left">@Html.DropDownListFor(x => main_model_list[i].SelectedEmp, new SelectList(main_model_list[i].dddl, "Id", "Value", main_model_list[i].SelectedEmp), new { @class = "preferences_dd_lists" })</div>
    }
}

【问题讨论】:

  • 你的 ajax 调用在哪里?
  • 如何输出视图?您是否偶然使用了foreach
  • 我正在使用 for 语句从 main_model_list 列表中传递所有元素及其属性。
  • @Aleks 你能显示你表单的html(查看源代码)吗?
  • @Aleks 你检查过 ajax 调用期间生成的 JSON 吗?它是否具有 MainModel 的正确属性?

标签: c# ajax asp.net-mvc jquery


【解决方案1】:

您可以更改您的代码。

data:{ model:$(this).serialize()}

因为你没有给出参数名,所以mvc模型绑定不起作用。

【讨论】:

    【解决方案2】:

    你可以尝试使用

      @using(Ajax.BeginForm("SaveModel", "controller", formMethod.Post, new AjaxOptions{ }))
      {
          // your form
      }
    

    别忘了使用 jquery.unobtrusive-ajax.js

    并且使用 Ajax.BeginForm,您可以删除该 jQuery 代码块来发送您的表单,它使您的表单直接绑定在 Action 中。

    【讨论】:

      【解决方案3】:

      尝试以下方法:

      $("#form").submit(function( ) {
            $.ajax({
              url: "/Controller/SaveModel",
              contentType: "application/json",
              type: "POST",
              data: $(this).serialize()
          });
      });
      

      【讨论】:

      • 我还是有同样的问题。
      【解决方案4】:

      在绑定活页夹时,正在寻找您未提供的值 ID。 所以在你的视图页面的循环中添加这个

      @Html.HiddenFor(x => x.main_model_list[i].Id)
      

      【讨论】:

        【解决方案5】:

        我确定你写错了 html,你想将一个集合发布到控制器,但是你的数据表单与你的模型不匹配。

        我认为如果你想向你的控制器发送一个集合,你必须修改你的 html-form 像这样:

        <input type="hidden" name="main_model_list[0].Id" value="1 />
        <input type="hidden" name="main_model_list[0].Name" value="xyz" />
        <select name="main_model_list[0].SelectedEmp">
        .....
        </select> 
        <input type="hidden" name="main_model_list[1].Id" value="1 />
        <input type="hidden" name="main_model_list[1].Name" value="xyz" />
        <select name="main_model_list[1].SelectedEmp>
        .....
        </select> 
        

        ..................

        我认为你应该从单个模型中删除 List dddl。

        【讨论】:

          【解决方案6】:

          我已经执行了下面的代码,它工作正常。如下声明模型

           public class SimpleDropdown
          {
              //
              // Summary:
              //     Gets or sets the text of the selected item.
              //
              // Returns:
              //     The text.
              public string Text { get; set; }
              //
              // Summary:
              //     Gets or sets the value of the selected item.
              //
              // Returns:
              //     The value.
              public string Value { get; set; }
          }
          
          public class SingleEntity
          {
              public int Id { get; set; }
              public string Name { get; set; }
              public List<SimpleDropdown> dddl { get; set; }
              public int SelectedEmp { get; set; }
          }
          
          public class MainModel
          {
              public List<SingleEntity> main_model_list { get; set; }
          }
          

          和Controller动作方法如下

          public class BasicController : Controller
          {
              public ActionResult GetModel()
              {
                  MainModel mainModel = new MainModel();
                  List<SimpleDropdown> dropdownlist = new List<SimpleDropdown>();
                  List<SingleEntity> selist = new List<SingleEntity>();
                  for (int j = 1; j < 10; j++)
                  {
                      dropdownlist.Add(new SimpleDropdown { Text = "Text" + j, Value = j.ToString() });
          
                  }
                  SingleEntity se;
                  for (int i = 0; i < 10; i++)
                  {
                      se = new SingleEntity();
                      se.Id = i;
                      se.Name = "Name" + i;
                      se.SelectedEmp = i;
                      se.dddl = dropdownlist;
                      mainModel.main_model_list = selist;
                      mainModel.main_model_list.Add(se);
          
                  }
                  return View(mainModel);
              }
          
              [HttpPost]
              public ActionResult SaveModel(MainModel mainModelasdfafsf)
              {
                  // do stuff here... please not only selectedEmp only will get reflected but not the property ddl since its again another list
                  return View("GetModel");
              }
          }
          

          最后视图应该是这样的

          @model MvcDemo.Models.MainModel
          @using (Html.BeginForm("SaveModel", "Basic", FormMethod.Post, new { id = "formModel" }))
          

          {

          for (var i = 0; i < Model.main_model_list.Count; i++)
          {
          <div>@Html.TextBoxFor(x => Model.main_model_list[i].Id)</div>
          <div>@Html.TextBoxFor(x => Model.main_model_list[i].Name)</div>
          <div>
              @Html.TextBoxFor(x => Model.main_model_list[i].SelectedEmp)
          </div>
          <div style="float: left">
              @Html.DropDownListFor(x => Model.main_model_list[i].SelectedEmp, new SelectList(Model.main_model_list[i].dddl, "Text", "Value", Model.main_model_list[i].SelectedEmp), new { @class = "preferences_dd_lists" })
          
          </div>
          
          }
          
          <input type="button" value="Save" id="btnsave" name="btnsave" />
          

          }

          @section Scripts{
          <script type="text/javascript">
              $(document).ready(function () {
                  $('#btnsave').click(function () {
                      $.ajax({
                          async: false,
                          cache: false,
                          data: $('#formModel').serialize(),
                          url: '@Url.Action("SaveModel", "Basic")',
                          type: "POST",
                          dataType: "text/html",
                          success: function () {
                              alert('success');
                          },
                          error: function (errorThrown) {
                              debugger;
                              alert('something went wrong!!!');
                          }
          
                      });
                  });
              });
          </script>
          

          }

          首先确保所有脚本文件都已加载,并且 Check this Link where Model binding will not work for Lable and LableFor

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-03-14
            • 2011-02-20
            • 2013-04-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多