简体   繁体   English

MVC模型绑定对象列表

[英]MVC Model Binding List of objects

I am having trouble binding a model that contains list of objects. 我无法绑定包含对象列表的模型。 There are no problems when i try to pass the data from the controller to the view, but when i want to send the data back, i get a message that the method doesnt exists. 当我尝试将数据从控制器传递到视图时没有问题,但是当我想要发回数据时,我得到一条消息,表明该方法不存在。

I am using an ajax call and as data i put $form.serialize() and can see the list with all the data in fiddler, but i am having no luck with the binding. 我正在使用ajax调用,并且作为数据我放了$ form.serialize()并且可以看到包含fiddler中所有数据的列表,但是我对绑定没有运气。

The Model is: 该模型是:

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

In my controller the method for now is: 在我的控制器中,现在的方法是:

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

This method doesn't get called, but when i remove the parameter the calling works. 此方法不会被调用,但是当我删除调用的参数时。 So i'm sure that the binding doesn't work. 所以我确定绑定不起作用。 I had a lot more complex model, but i simplified it as much as i can and still couldn't get it to work. 我有一个更复杂的模型,但我尽可能简化它,仍然无法让它工作。

So my question is how can i test this to see what is the problem? 所以我的问题是如何测试这个以查看问题是什么?

Edit: 编辑:

I dont have the code at the moment, but that code is functional because i use it in other places in the project. 我目前没有代码,但该代码功能正常,因为我在项目的其他地方使用它。 It is something like this: 它是这样的:

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

The form looks something like this: 表单看起来像这样:

@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>
    }
}

You can try to use 你可以尝试使用

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

Don't forget use the jquery.unobtrusive-ajax.js 不要忘记使用jquery.unobtrusive-ajax.js

and with Ajax.BeginForm you can remove that block of jQuery code to send your form, and it makes that your form be bind directly in the Action. 并且使用Ajax.BeginForm,您可以删除该jQuery代码块以发送您的表单,并使您的表单直接在Action中绑定。

You can change your code. 您可以更改代码。

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

Because you don't give the parameter name, the mvc model binding do not work. 因为您没有提供参数名称,所以mvc模型绑定不起作用。

Try the following: 请尝试以下方法:

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

while binding the binder is looking for value Id which was not provided by you. 绑定绑定器时正在查找未由您提供的值Id。 so add this in the loop in your view page 所以在视图页面的循环中添加它

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

I'm sure that you wrote html wrongly, you want to post a collection to controller , but your data-form doesn't match with your model. 我确定您错误地编写了html,您希望将一个集合发布到控制器,但您的数据表单与您的模型不匹配。

I think if you want to send a collection to your controller you have to modify your html-form like that: 我想如果你想将一个集合发送到你的控制器,你必须修改你的html表单:

<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> 

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

And I think you should remove List dddl from single model. 我认为你应该从单一模型中删除List dddl。

I have executed below code it is working fine. 我执行下面的代码它工作正常。 Declare Model(s) as below 声明模型如下

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

And Controller action methods are as follows 而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");
    }
}

And Finally View should be something like this 最后,View应该是这样的

@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>

} }

Above All make sure all the script files are loaded and also Check this Link where Model binding will not work for Lable and LableFor 以上全部确保加载所有脚本文件,并检查此链接,其中模型绑定不适用于Lable和LableFor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM