c# - ASP.NET MVC 使用 UIHint 属性生成 DropDownList

标签 c# asp.net asp.net-mvc attributes asp.net-mvc-uihint

我想知道如何使用 UIHint 属性生成 DropDownList。我已经自定义了一些预定义的属性,但我不知道如何继续生成 DropDownList。

这是我对上一个的处理方式,我想以类似的方式使用它:

public class CartProduct
{

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

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

}

最佳答案

这是一个使用泛型的(未经测试的)一般示例。可能有更简单的方法来实现同样的目标。

型号:

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

Controller :

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 指定编辑器模板并在各处重用 View 。

关于c# - ASP.NET MVC 使用 UIHint 属性生成 DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22386710/

相关文章:

c# - 将 NULL 值分配给 SqlParameter 的最佳方法

c# - EnitityFramework 比较字符串的速度非常慢,因为创建了 nvarchar sqlparameter 而不是 varchar

javascript - Globalize.js 十进制数字验证的值错误

c# - PayPal 即时付款通知 (IPN) 不工作 ASP.NET C#

asp.net - 一键执行客户端和服务器端代码?

c# - 具有身份的 ASP.NET Core 中的自定义 RoleProvider?

c# - 发送附件时无法访问已关闭的流

c# - 使用 nunit 测试属性是否抛出异常

c# - DateTime 数据,分成几天

c# - KeyVaultClient 在调试时随机抛出 FatalExecutionEngineError