【发布时间】:2017-01-21 13:52:35
【问题描述】:
假设我在 SQL Server 中有一个 City 表。 这是 HomeController:
[HttpGet]
public ActionResult Index()
{
SampleDBContex db = new SampleDBContex();
return View(db.Cities);
}
[HttpPost]
public string Index(IEnumerable<City> cities)
{
if (cities.Count(x => x.IsSelected) == 0)
{
return "You didn't select city";
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append("You selected -");
foreach (City city in cities)
{
if (city.IsSelected)
{
sb.Append(city.Name + ", ");
}
}
sb.Remove(sb.ToString().LastIndexOf(","), 1);
return sb.ToString();
}
}
}
这是索引视图(get 方法):
@model IEnumerable<Part38MVCCheckBoxList.Models.City>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
@Html.EditorForModel()
<br />
<input type="submit" value="Submit" />
}
这是编辑器模板:
@model Part38MVCCheckBoxList.Models.City
@Html.HiddenFor(x => x.ID)
@Html.HiddenFor(x => x.Name)
@Html.CheckBoxFor(x => x.IsSelected)
@Html.DisplayFor(x => x.Name)
我不明白为什么我们需要使用@Html.HiddenFor(x => x.Name),否则它无法显示城市名称。我认为我们通过模型 IEnumerable 所以我们应该已经存在城市名称当我们从数据库中检索它们时
【问题讨论】: