我有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" />
}
什麼是顯示視圖時,你所面臨的問題? – niksofteng
我會添加我的視圖。我試圖用for循環顯示列表,但我總是得到一個NULL異常。 – Drummer
調試你的視圖剃鬚刀,看看你在'模型'中得到了什麼? – niksofteng