是否存在将项目的IList绑定到视图的模式。我的HttpPost似乎有点问题。我知道Phil Haack写了一篇很好的文章,但它已经过时了,他说他们可能会修复MVC4。
发布于 2013-03-13 10:25:17
如果我需要为每个项目显示一个表单,并为各种属性输入,我就是这样做的。这真的取决于我想做什么。
ViewModel看起来像这样:
public class MyViewModel
{
public List<Person> Persons{get;set;}
}视图(当然是使用BeginForm ):
@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)
{
...请注意,在回发时,只有具有可用输入的属性才会有值。也就是说,如果Person有一个.SSN属性,那么它在post操作中将不可用,因为它不是表单中的一个字段。
请注意,MVC的模型绑定的工作方式是,它只查找连续的ID。因此,在有条件地隐藏项的情况下,这样做将导致它不绑定第5项之后的任何数据,因为一旦遇到ID的间隙,它将停止绑定。即使有10个人,你也只能在回发时得到前4个:
@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)
}
}发布于 2014-04-17 03:55:45
一个干净的解决方案是创建一个泛型类来处理列表,这样您就不需要在每次需要时都创建一个不同的类。
public class ListModel<T>
{
public List<T> Items { get; set; }
public ListModel(List<T> list) {
Items = list;
}
}当您返回View时,您只需简单地执行以下操作:
List<customClass> ListOfCustomClass = new List<customClass>();
//Do as needed...
return View(new ListModel<customClass>(ListOfCustomClass));然后在模型中定义列表:
@model ListModel<customClass>准备好了:
@foreach(var element in Model.Items) {
//do as needed...
}发布于 2013-03-13 11:28:41
~控制器
namespace ListBindingTest.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
List<String> tmp = new List<String>();
tmp.Add("one");
tmp.Add("two");
tmp.Add("Three");
return View(tmp);
}
[HttpPost]
public ActionResult Send(IList<String> input)
{
return View(input);
}
}
}~强类型索引视图
@model IList<String>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using(Html.BeginForm("Send", "Home", "POST"))
{
@Html.EditorFor(x => x)
<br />
<input type="submit" value="Send" />
}
</div>
</body>
</html>~强类型发送视图
@model IList<String>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Send</title>
</head>
<body>
<div>
@foreach(var element in @Model)
{
@element
<br />
}
</div>
</body>
</html>这就是你所要做的,把他的MyViewModel模型改成IList。
https://stackoverflow.com/questions/15375800
复制相似问题