ASP.NET MVC使用生成的DropDownList UIHint属性 [英] ASP.NET MVC Generate DropDownList using UIHint Attribute

查看:802
本文介绍了ASP.NET MVC使用生成的DropDownList UIHint属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道怎样才能使用UIHint属性一个DropDownList。我已经定制了一些predefined属性,但我不知道如何着手生成DropDownLists。

下面是我如何用我最后一次做,我想以类似的方式来使用它:

 公共类CartProduct
{    [需要]
    [UIHint(微调)]
    公众诠释?数量{搞定;组; }    [需要]
    [UIHint(MultilineText)]
    公共字符串描述{搞定;组; }}


解决方案

下面是一个使用泛型的(未经测试)一般的例子。有可能实现同样的事情的一个简单的方法。

型号:

 公共类CartProduct
{
    [UIHint(_ DropDownList的)]
    公共DropDownListModel<&的ItemType GT; MyItems {搞定;组; }
}

DropDownListModel类:

 公共类DropDownListModel< T>
{
    公共ŧ的SelectedItem {搞定;组; }    公共IEnumerable的< T>项目{搞定;组; }
}

控制器:

 公众的ActionResult AnAction()
{
    VAR模型=新CartProduct();
    model.MyItems =新DropDownListModel<&的ItemType GT;
    {
        项目= _yourListOfItems,
        的SelectedItem = _yourSelectedItem
    };    返回查看(模型);
}

_DropDownList.cshtml编辑模板:

  @model DropDownListModel<对象>@ Html.DropDownListFor(M = GT; m.SelectedItem,
    新的SelectList(Model.Items,Model.SelectedItem))

最后,您的看法:

  @model CartProduct@ Html.EditorFor(M = GT; m.MyItems)

这为您提供了一个通用的 DropDownListModel ,你可以在任何地方使用,与任何类型的。使用 EditorFor UIHint 来指定编辑模板和重用的观点得到处都是。

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; }

}

解决方案

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.

这篇关于ASP.NET MVC使用生成的DropDownList UIHint属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆