3 回答

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
一個(gè)干凈的解決方案可以創(chuàng)建一個(gè)通用類來(lái)處理列表,因此您不需要在每次需要時(shí)創(chuàng)建不同的類。
public class ListModel<T>
{
public List<T> Items { get; set; }
public ListModel(List<T> list) {
Items = list;
}
}
當(dāng)您返回視圖時(shí),您只需要執(zhí)行以下操作:
List<customClass> ListOfCustomClass = new List<customClass>();
//Do as needed...
return View(new ListModel<customClass>(ListOfCustomClass));
然后在模型中定義列表:
@model ListModel<customClass>
準(zhǔn)備好了:
@foreach(var element in Model.Items) {
//do as needed...
}

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
?控制器
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);
}
}
}
?強(qiáng)類型索引視圖
@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>
?強(qiáng)類型發(fā)送視圖
@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。
- 3 回答
- 0 關(guān)注
- 433 瀏覽
添加回答
舉報(bào)