继续在无缝简单的问题上敲打我的头。有人可以为我写完整的代码:
2个型号:
public class State
{
public int StateID { get; set; }
public string Name { get; set; }
}
public class City
{
public int CityID { get; set; }
public string Name { get; set; }
public int StateID { get; set; }
[ForeignKey("StateID")]
public State State { get; set; }
public IEnumerable<SelectListItem> StateList { get; set; }
}
剩下的就是问题了。如何编写 ViewModel、Index ActionResult 和 View?我在内置测试环境中使用 EF。
我只是用完了组合来尝试:(
#这是我的最终解决方案: ViewModel
public class CityIndexViewModel
{
public int CityID { get; set; }
public string CityName { get; set; }
public int StateId { get; set; }
public string StateName { get; set; }
}
控制器
public ActionResult Index()
{
var model = new List<CityIndexViewModel>();
var dbCity = db.City.Include("State");
foreach (City c in dbCity)
{
var cityIndex = new CityIndexViewModel()
{
CityID = c.CityID,
CityName = c.Name,
StateId = c.State.StateID,
StateName = c.State.Name
};
model.Add(cityIndex);
}
return View(model);
}
看法
@model IEnumerable<app.ViewModel.CityIndexViewModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Citys
@*@Html.DisplayNameFor(model => model.Citys)*@
</th>
<th>
States
@*@Html.DisplayNameFor(model => model.States)*@
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.CityName)
</td>
<td>
@Html.DisplayFor(modelItem => item.StateName)
</td>
<td>
@* @Html.ActionLink("Edit", "Edit", new { id=item.CityID }) |
@Html.ActionLink("Details", "Details", new { id=item.CityID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.CityID })*@
</td>
</tr>
}
</table>