模型绑定到一个List MVC 4 [英] Model Binding to a List MVC 4

查看:126
本文介绍了模型绑定到一个List MVC 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有绑定项目视图一个IList的模式。我似乎有与HttpPost问题。我知道菲尔哈克写了一篇好文章,但它是过时,他说,他们可能有一个修复与MVC 4。

Is there a pattern to bind an IList of items to the view. I seem to be having issues with the HttpPost. I know Phil Haack wrote a nice article but it is dated and he said they might have a fix with MVC 4.

推荐答案

这是我要做的事,如果我需要的各种特性,每个项目显示的一种形式,和投入。实际上取决于我想要做虽然。

This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what I'm trying to do though.

视图模型看起来是这样的:

ViewModel looks like this:

public class MyViewModel
{
   public List<Person> Persons{get;set;}
}

查看(当然,BeginForm):

View(with BeginForm of course):

@model MyViewModel


@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    @Html.HiddenFor(m => m.Persons[i].PersonId)
    @Html.EditorFor(m => m.Persons[i].FirstName) 
    @Html.EditorFor(m => m.Persons[i].LastName)         
}

动作:

[HttpPost]public ViewResult(MyViewModel vm)
{
...

注意,在回发只是其中有可将输入值的属性。即,如果人有一个.SSN属性,它不会是在后可用的行动,因为它不是在形式的领域。

Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasn't a field in the form.

请注意,该办法MVC模型结合的作品,它只会看连续的ID。所以,做这样的事情,你有条件地隐藏项将导致它不是第五项之后的任何数据绑定,因为一旦它遇到的ID的差距,就会停止绑定。即使有10个人,你只会在回发得到的第一个4:

Note that the way MVC's model binding works, it will only look for consecutive ID's. So doing something like this where you conditionally hide an item will cause it to not bind any data after the 5th item, because once it encounters a gap in the IDs, it will stop binding. Even if there were 10 people, you would only get the first 4 on the postback:

@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    if(i != 4)//conditionally hide 5th item, 
    { //but BUG occurs on postback, all items after 5th will not be bound to the the list
      @Html.HiddenFor(m => m.Persons[i].PersonId)
      @Html.EditorFor(m => m.Persons[i].FirstName) 
      @Html.EditorFor(m => m.Persons[i].LastName)           
    }
}

这篇关于模型绑定到一个List MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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