【发布时间】:2016-02-21 07:49:05
【问题描述】:
我有 2 个模型。在第一个模型中,“Checkmodel”描述了对象的外观。 第二个模型“Checkmodels”基于“Checkmodel”创建对象列表。
现在我尝试在我的视图中显示它,但我不知道该怎么做。
- 型号“Checkmodel”
namespace WebAppMVCtests.Models { public class CheckModel { public string Name { get; set; } public bool IsChecked { get; set; } public CheckModel(string name, bool ischecked) { this.Name = name; this.IsChecked = ischecked; } } }
- 型号“Checkmodels”
namespace WebAppMVCtests.Models { public class CheckModels : List<CheckModel> { private List<CheckModel> modellist; public CheckModels() { modellist = new List<CheckModel>(); } public void Add(string name, bool ischecked) { CheckModel newModel = new CheckModel(name, ischecked); this.Add(newModel); } } }
控制器
namespace WebAppMVCtests.Controllers
{
public class HomeController : Controller
{
// GET: Home
[HttpGet]
public ActionResult Index()
{
CheckModels chmdls = new CheckModels();
List<string> e = new List<string>();
e.Add("John");
e.Add("Kevin");
e.Add("Mark");
string name = "";
bool ischecked = false;
foreach (var dir in e)
{
CheckModel newCheckModel = new CheckModel(name, ischecked);
chmdls.Add(newCheckModel);
}
return View();
}
[HttpPost]
public ActionResult Index(List<CheckModel> list)
{
return View();
}
}
}
查看
@model WebAppMVCtests.Models.CheckModels
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
for (var i = 0; i < Model.Count(); i++)
{
<table>
<tr>
<td>
@Html.DisplayFor(it => it[i].Name)
</td>
<td>
@Html.CheckBoxFor(it => it[i].IsChecked)
</td>
</tr>
</table>
}
<input id="Submit1" type="submit" value="submit" />
}
【问题讨论】:
-
视图显示时遇到什么问题?
-
我将添加我的观点。我尝试使用 for 循环显示列表,但总是出现 NULL 异常。
-
调试你的视图剃刀,看看你在
Model得到了什么? -
我得到 NULL 但我不明白为什么。在控制器中,我创建对象,然后将它们放入列表中。
标签: c# list model-view-controller web-applications