【问题标题】:ASP.NET MVC2 custom controlASP.NET MVC2 自定义控件
【发布时间】:2011-02-03 21:06:39
【问题描述】:

哪种是创建自定义表单控件(如自定义下拉菜单)的正确 MVC 方式? 我需要一种方法来创建这样的控件并在几页中重新使用它。我想使用默认活页夹 在调用 action 方法时绑定选定的值。 有人可以举一个简单的例子吗?

这是我目前的解决方案,我认为它的设计不是很好。

DropDownViewModel.cs

class DropDownViewModel {
    ...
    public string BindName {get; set;} // the name that default binder uses to bind to action param
    public int SelectedValue {get;set;} // this value should be set when user use the drop down
    ...
}

DropDown.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DropDownViewModel>" %>
...
<%= Html.TextBox(Model.BindName) %> 
...

当我尝试将此 DropDownViewModel 包含到其他视图模型中时,问题就出现了:

GeneralUserInfoViewModel.cs

class GeneralUserInfoViewModel {
    ...
    public DropDownViewModel Gender {get;set;}
    ...
}

AccountController.cs

...
public ActionResult EditGeneralUserInfo(GeneralUserInfoViewModel info) { 

}
...

要正常工作,BindName 应该设置为“Gender.SelectedValue”。这可以通过在 RegisterUserViewModel 中设置 BindName 来解决。但是,如果 GeneralUserInfoViewModel 是另一个视图模型的一部分,例如:

RegisterUserViewModel.cs

class RegisterUserViewModel {
    ...
    public GeneralUserInfoViewModel GeneralInfo {get;set;}
    ...
}

现在应该将 BindName 设置为“GeneralInfo.Gender.SelectedValue”,以便与默认活页夹正常工作:

...
public ActionResult RegisterUser(RegisterUserViewModel info) { ... }
...

等等。 如何处理这种分层?如何确定在 DropDownVoewModel 中应将什么设置为 BindName attr?还是有其他更好的实现方式?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-2


    【解决方案1】:

    最常见的方法是:

    • 创建一个htmlhelper,您可以调用它来呈现您的控件。这是最强大和最干净的方法,但也相当繁琐,因为您需要在 c# 中组装 html 标记。

    • 将控件放在部分页面中并调用 Html.RenderPartial 或 Html.Partial 来呈现它。这样做的好处是您可以编写 html 标记。它比 c# html helpers 更容易且可读性更好。

    您也可以将两者混合使用。或者将第二种方法与基于强的视图模型一起使用,让视图模型进行初始化,从而为您提供这些方法之间的一种混合。

    ASP.NET MVC 3 还引入了一种新的 html 帮助器,它更适合构建可重用的控件库。好处是您可以在 Razor 视图引擎标记中编写 html 助手。详情请见this blog article

    编辑: 我实现通用 ajaxed 下拉列表的方式实际上与我上面提到的两种不同。它的工作原理如下:

    1. 为下拉列表创建编辑器模板
    2. 使用 Html.EditorFor() 呈现编辑器模板
    3. 我的模型的每个下拉列表有两个属性:值和选项。该值使用 DisplayHint 属性进行修饰,以便始终使用下拉列表编辑器模板呈现它

    ASP.NET MVC 会自动处理任何模型上下文前缀。如果您不熟悉编辑器模板:Brad Wilson 写了一个非常好的blog article series 来说明这一点。

    【讨论】:

    • @RPM1984:感谢您的公平和诚实!
    • 我实际上混合使用了您描述的两种方法,但我有不同的问题 - 请阅读编辑
    猜你喜欢
    • 1970-01-01
    • 2010-09-23
    • 2011-06-15
    • 2011-01-21
    • 1970-01-01
    • 2011-12-20
    • 2012-06-07
    • 1970-01-01
    相关资源
    最近更新 更多