MVC4 中的Model显示设置(含显示Shared/DisplayTemplates和编辑Shared/EditorTemplates) MVC4 中的Model显示设置(含显示Shared/DisplayTemplates和编辑Shared/EditorTemplates)

转载于:

MVC4 中的Model显示设置(含显示Shared/DisplayTemplates和编辑Shared/EditorTemplates)

   虽然 [Display(Name="XXX")]已经能在页面中@Html.LabelFor(m=m.属性)中显示其值,但是不够灵活,特别是在@Html.EtitorForModel()或@Html.DisplayForModel()时,我们想要根据自己的要求来显示信息,那么我们就要根据情况

   实现步骤如下:

    1. 在View 下的shared文件夹下添加EditorTemplates文件夹

    2.在EditorTemplates 添加视图(不继承任何模板)  如添加 视图 YesOrNo.cshtml

    3.给YesOrNo.cshtml添加处理代码如:用户填写是否已婚,这时我们要在该bool类型值的在页面中以@Html.RadioButton()的方式

      来让用户选择这时我们可以在YesOrNo.cshtml写如下代码

@model bool
@Html.RadioButton("",true,Model)是
@Html.RadioButton("",false,!Model)否

    4.在Model中使用UIHint("SetView")中的SetView来显示Model中的当前属性,代码如下

        [UIHint("YseOrNo")]
        public bool YesOrNo { get; set; }

    5.在编辑页面中我们只要在Form中使用@Html.EtitorForModel()来显示就可以了

复制代码
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@model MvcApplication1.Models.User
@using (Html.BeginForm())
{ 
    @Html.EditorForModel()
    @Html.EditorFor(m=>m.list)
    <input type="submit" value="提交" />
}
复制代码

注意上面 的一个人对应多个朋友时的情况也要通过上面的方式UIHint来设置显示,由于是一对多的关系,所以无法显示,这时我们要手动添

加@Html.EditorFor(m=>m.list),的setView(也就是在EditorTemplates文件夹添加的MyFriend.cshtml)代码如下

复制代码
@model IEnumerable<MvcApplication1.Models.Friend>
<div>
     @foreach (var item in Model)
     { 
         <div>
                  @Html.LabelFor(m=>item.Name):@Html.TextBoxFor(m=>item.Name)
                  @Html.LabelFor(m=>item.Age):@Html.TextBoxFor(m=>item.Age)
         </div>
     }
</div>
复制代码

Mode 中的对应关系

复制代码
        [UIHint("MyFriend")]
        public List<Friend> list { get; set; }
    }

    public class Friend
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
复制代码

关于枚举或类的对应在上述过程中的运用   Model中

复制代码
        [UIHint("MyRole")]
        public Role role { get; set; }

    }

    public enum Role
    { 
        admin,
        pm,
        one,
    }
复制代码

在 EditorTemplates文件夹添加MyRole.cshtml中的代码

复制代码
@model MvcApplication1.Models.Role
<select id="role" name="role">
    @foreach(MvcApplication1.Models.Role item in Enum.GetValues(typeof(MvcApplication1.Models.Role)))
    {
        <option value="@item" @(Model==item?"selected=true":"")>@item</option>
    }
</select>
复制代码

类也一样做,也可以使用ViewData来做文章

猜你喜欢

转载自www.cnblogs.com/0to9/p/9977884.html
今日推荐