MVC4 中的Model顯示設定(含顯示Shared/DisplayTemplates和編輯Shared/EditorTemplates)

來源:互聯網
上載者:User

標籤:style   blog   color   使用   檔案   io   

   雖然 [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來做文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.