MVC5从Linq到ViewModel到Razor视图的代码改进

本文关键字:代码 视图 Razor Linq ViewModel MVC5 | 更新日期: 2023-09-27 18:06:41

我想从两个EF表(菜单和菜单项)中获取数据。然后我想把结果放入ViewModel。所以我可以很容易地在Razor视图中循环遍历数据。

我已经让它工作了。但我是新的。net MVC,所以我想知道我的代码可以改进。也许这些查询可以合并,并且更短。我正在使用AsEnumerable(),我不确定这是否是最好的方法。

我认为我的尝试是好的。但我想听听你的想法。欢迎对代码改进提出任何建议。谢谢。

控制器类:

   public ActionResult Index(int? id)
        {
            if (id == null) return RedirectToAction("Index", new { controller = "Menu"      });
        var menu =
            (from m in _db.Menus
             join mi in _db.MenuItems on m.Id equals mi.MenuId
             where m.Id == id
             select m).First();
        var menuItems =
            (from mi in _db.MenuItems.AsEnumerable()
             join m in _db.Menus on mi.MenuId equals m.Id
             where m.Id == id
             select new MenuItem
             {
                 Id = mi.Id,
                 Name = mi.Name,
                 Href = mi.Href,
                 CssClass = mi.CssClass,
                 CssId = mi.CssId,
                 Title = mi.Title,
                 Weight = mi.Weight
             });
        var model = new MenuModelView
        {
            Id = menu.Id,
            Name = menu.Name,
            CssClass = menu.CssClass,
            CssId = menu.CssId,
            Deleted = menu.Deleted,
            MenuItems = menuItems
        };
        return View(model);
    }

ViewModel类:

using System.Collections.Generic;
namespace DesignCrew.Areas.Admin.Models
{
    public class MenuModelView
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string CssClass { get; set; }
        public string CssId { get; set; }
        public bool Deleted { get; set; }
        public IEnumerable<MenuItem> MenuItems { get; set; }
    }
}

The Razor View:

@model DesignCrew.Areas.Admin.Models.MenuModelView
@{
    ViewBag.Title = "Index";
}
<h2>Menu - @Html.DisplayFor(model => model.Name, new { @class = "control-label col-md-2" })</h2>
<p>
    @Html.ActionLink("Create New Item", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.MenuItems.First().Id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MenuItems.First().Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MenuItems.First().Href)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MenuItems.First().Title)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MenuItems.First().CssClass)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MenuItems.First().CssId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MenuItems.First().ParentId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MenuItems.First().Weight)
        </th>
        <th>Options</th>
    </tr>
    @foreach (var item in Model.MenuItems)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Href)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CssClass)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CssId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ParentId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Weight)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "link-menu" }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @class = "link-menu" })
            </td>
        </tr>
    }
</table>

MVC5从Linq到ViewModel到Razor视图的代码改进

如果你的EF模型在MenuMenuItem之间有一个可导航的外键,你不需要显式地连接这两个表,你可以在获取父Menu的同时急切地加载子MenuItems,并简单地从父导航到子:

var menu = _db.Menus
              .Include("MenuItems") // Or, use the typed version on newer EF's
              .First(m => m.id == id); // Many LINQ expressions allow predicates
return new MenuModelView
 {
    Menu = menu.Name,
    CssClass = menu.CssClass,
    CssId = menu.CssId,
    Deleted = menu.Deleted,
    MenuItems = menu.MenuItems
 }

而且,由于MenuModelViewMenu EF实体之间似乎有很多共同点,您可以考虑使用AutoMapper。一旦配置好,这将允许您用以下内容替换手动映射步骤:

return Mapper.Map<Menu, MenuModelView>(menu);

编辑

这是一个便宜而讨厌的ViewModel,它包装了你的EF实体,并用表示层数据来增强它。纯粹主义者可能会注意到,您应该为包装的EF模型创建新类,尽管您的EF模型似乎建模Html:)

public class MenuModelView
{
   // Presentation tier stuff
   public string PageTitle { get; set; }
   public string MetaTagsForSEO { get; set; }
   public bool IsThisARegisteredUserSoSkipTheAdverts { get; set; }
   // Your EF / Domain Model
   public Menu Menu { get; set; }
}

你的剃刀@Model就是MenuModelView