3

I would like to know how can I generate a DropDownList using an UIHint attribute. I already customized some of the predefined attributes but I don't know how to proceed for generating DropDownLists.

Here is how I did with my last one and I want to use it in a similar way:

public class CartProduct
{

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

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

}
tzortzik
  • 4,993
  • 9
  • 57
  • 88
  • What property do you want in a DropDownList? What have you tried? Where's your code? All I see is a class with two presumably unrelated properties. – Ant P Mar 13 '14 at 18:38
  • 1
    Yes, I showed an example with how I proceeded with other attributes. That's the way I want to apply `UIHint("DropDownList")` to a property. But for doing this I really have no idea on how to create such attribute. – tzortzik Mar 13 '14 at 19:19

1 Answers1

8

Here's an (untested) general example using generics. There's probably a simpler way of achieving the same thing.

Model:

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

DropDownListModel class:

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

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

Controller:

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

    return View(model);
}

_DropDownList.cshtml editor template:

@model DropDownListModel<object>

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

And, finally, your view:

@model CartProduct

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

This gives you a generic DropDownListModel that you can use anywhere, with any type. Use EditorFor and UIHint to specify the editor template and reuse the view all over the place.

Ant P
  • 24,820
  • 5
  • 68
  • 105