模型绑定到列表MVC 4

是否有将IList项绑定到视图的模式。我似乎遇到了HttpPost的问题。我知道菲尔哈克写了一篇很好的文章,但它已经过时了,他说他们可能会修复MVC 4。



慕尼黑的夜晚无繁华
浏览 403回答 3
3回答

繁花如伊

一个干净的解决方案可以创建一个通用类来处理列表,因此您不需要在每次需要时创建不同的类。public class ListModel<T>{&nbsp; &nbsp; public List<T> Items { get; set; }&nbsp; &nbsp; public ListModel(List<T> list) {&nbsp; &nbsp; &nbsp; &nbsp; Items = list;&nbsp; &nbsp; }}当您返回视图时,您只需要执行以下操作:List<customClass> ListOfCustomClass = new List<customClass>();//Do as needed...return View(new ListModel<customClass>(ListOfCustomClass));然后在模型中定义列表:@model ListModel<customClass>准备好了:@foreach(var element in Model.Items) {&nbsp; //do as needed...}

慕尼黑5688855

〜控制器namespace ListBindingTest.Controllers{&nbsp; &nbsp; public class HomeController : Controller&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; // GET: /Home/&nbsp; &nbsp; &nbsp; &nbsp; public ActionResult Index()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<String> tmp = new List<String>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tmp.Add("one");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tmp.Add("two");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tmp.Add("Three");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return View(tmp);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; [HttpPost]&nbsp; &nbsp; &nbsp; &nbsp; public ActionResult Send(IList<String> input)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return View(input);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }}〜强类型索引视图@model IList<String>@{&nbsp; &nbsp; Layout = null;}<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>Index</title></head><body>&nbsp; &nbsp; <div>&nbsp; &nbsp; @using(Html.BeginForm("Send", "Home", "POST"))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; @Html.EditorFor(x => x)&nbsp; &nbsp; &nbsp; &nbsp; <br />&nbsp; &nbsp; &nbsp; &nbsp; <input type="submit" value="Send" />&nbsp; &nbsp; }&nbsp; &nbsp; </div></body></html>〜强类型发送视图@model IList<String>@{&nbsp; &nbsp; Layout = null;}<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>Send</title></head><body>&nbsp; &nbsp; <div>&nbsp; &nbsp; @foreach(var element in @Model)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; @element&nbsp; &nbsp; &nbsp; &nbsp; <br />&nbsp; &nbsp; }&nbsp; &nbsp; </div></body></html>这就是你必须做的所有事情,将他的MyViewModel模型更改为IList。
打开App,查看更多内容
随时随地看视频慕课网APP