MVC4 ViewModel从数据库中查看 - 示例

时间:2013-08-04 17:15:38

标签: asp.net-mvc-4 model-view

坚持不懈地解决简单的问题。有人可以写我完整的代码:

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。

我只是尝试用完组合:(

这是我的最终解决方案: 的视图模型

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>

0 个答案:

没有答案