2013-07-20 29 views
1

我的工作MVC4using @Html.EditorForModel(),它顯示dropdownlist爲文本框,我想通過設置任何attribute和壓倒一切的模板顯示Dropdown列表。請與我分享MVC4這個例子。@ Html.EditorForModel()下拉

@model Models.Employee 

@{ 
    ViewBag.Title = "Create"; 
} 

<h2>Create</h2> 

@using (Html.BeginForm()) { 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>Employee</legend> 
     @Html.EditorForModel() 
     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 

在此先感謝。

回答

4

你可以定義視圖模式,將代表一個下拉菜單:

public class ItemsViewModel 
{ 
    public string SelectedValue { get; set; } 

    public IEnumerable<SelectListItem> Values { get; set; } 
} 

public class MyViewModel 
{ 
    public ItemsViewModel DropDown1 { get; set; } 
    public ItemsViewModel DropDown2 { get; set; } 
    ... 
} 

現在,所有剩下的就是寫的ItemsViewModel該建議立即進行刪除自定義編輯器模板:這將在主視圖模型被使用d被置於~/Views/Shared/EditorTemplates/ItemsViewModel.cshtml。請注意,模板的名稱和位置很重要:

@model ItemViewModel 
@Html.DropDownListFor(x => x.SelectedValue, Model.Values) 

而且這幾乎都是需要的。

+0

嗨,我使用@ HTML.EditorForModel()這意味着它加載模型運行時,沒有代碼 –

+2

當然,在我的例子中,模型是「MyViewModel」。你在主視圖中的所有內容是:'@model MyViewModel @ Html.EditorForModel()'。 –

+1

更清晰我編輯了代碼 –

-1

這是最重要的模板嗎?你可以使用@Html.DropDownList()幫手。

有一個關於如何在asp.net網站上使用,你可以下載該項目一個完整的例子:Here

+0

我正在尋找類似的方式來重寫MVC4,它是MVC2中的舊版本,現在無法工作。 http://weblogs.asp.net/rashid/archive/2009/11/27/extending-asp-net-mvc-2-templates.aspx –