2014-03-13 112 views
2

我想知道怎樣才能使用UIHint屬性一個DropDownList DropDownList的。我已經定製了一些預定義的屬性,但我不知道如何繼續生成DropDownLists。ASP.NET MVC生成使用UIHint屬性

這裏是我與我的最後一個沒有和我想以類似的方式來使用它:

public class CartProduct 
{ 

    [Required] 
    [UIHint("Spinner")] 
    public int? Quantity { get; set; } 

    [Required] 
    [UIHint("MultilineText")] 
    public string Description { get; set; } 

} 
+0

你想在DropDownList中使用什麼屬性?你有什麼嘗試?你的代碼在哪裏?我看到的只是一個有兩個可能無關的屬性的類。 –

+1

是的,我展示了一個如何繼續處理其他屬性的例子。這就是我想要將'UIHint(「DropDownList」)'應用於屬性的方式。但是爲了做到這一點,我真的不知道如何創建這樣的屬性。 – tzortzik

回答

8

下面是使用泛型的(未經測試)普通例子。實現同樣的事情可能有一個更簡單的方法。

型號:

public class CartProduct 
{ 
    [UIHint("_DropDownList")] 
    public DropDownListModel<ItemType> MyItems { get; set; } 
} 

DropDownListModel類:

public class DropDownListModel<T> 
{ 
    public T SelectedItem { get; set; } 

    public IEnumerable<T> Items { get; set; } 
} 

控制器:

public ActionResult AnAction() 
{ 
    var model = new CartProduct(); 
    model.MyItems = new DropDownListModel<ItemType> 
    { 
     Items = _yourListOfItems, 
     SelectedItem = _yourSelectedItem 
    }; 

    return View(model); 
} 

_DropDownList.cshtml編輯模板:

@model DropDownListModel<object> 

@Html.DropDownListFor(m => m.SelectedItem, 
    new SelectList(Model.Items, Model.SelectedItem)) 

最後,您的看法:

@model CartProduct 

@Html.EditorFor(m => m.MyItems) 

這給你一個通用的DropDownListModel,你可以在任何地方使用,與任何類型的。使用EditorForUIHint來指定編輯器模板並在整個地方重新使用該視圖。