【问题标题】:creating strongly type custom html helper?创建强类型自定义 html 助手?
【发布时间】:2013-04-08 10:45:29
【问题描述】:

我为出生日期创建了自定义助手,如下所示。

自定义 Html 帮助方法

public static MvcHtmlString DateOfBirthFor(this HtmlHelper html, string id ,int minYear, int maxYear, object htmlAttribute = null)
    {
        RouteValueDictionary attributes = new RouteValueDictionary(htmlAttribute);

        var days = Enumerable.Range(1, 31).Select(x => new SelectListItem
        {
            Value = x.ToString(),
            Text = x.ToString()
        });
        var months = Enumerable.Range(1, 12).Select(x => new SelectListItem
        {
            Value = x.ToString(),
            Text = x.ToString()
        });
        var years = Enumerable.Range(minYear, maxYear-(minYear-1)).Select(x => new SelectListItem
        {
            Value = x.ToString(),
            Text = x.ToString()
        });

        var mainDivTag = new TagBuilder("div");
        mainDivTag.MergeAttribute("id", id);
        mainDivTag.MergeAttributes(attributes);
        mainDivTag.InnerHtml = string.Concat(
            html.DropDownList("Day", days, new { style="width : 40px "}).ToHtmlString(),
            html.DropDownList("Month", months, new { style = "width : 40px " }).ToHtmlString(),
            html.DropDownList("Year", years, new { style = "width : 60px " }).ToHtmlString()
        );

        return new MvcHtmlString(mainDivTag.ToString());
    }

我还为同一个控件编写了自定义活页夹。

protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
    {
        if (propertyDescriptor.Name == "DateOfBirth")
        {
            DateTime dob = new   DateTime(int.Parse(controllerContext.HttpContext.Request.Form["Year"]), int.Parse(controllerContext.HttpContext.Request.Form["Month"]), int.Parse(controllerContext.HttpContext.Request.Form["Day"]));
            propertyDescriptor.SetValue(bindingContext.Model, dob);
        }

}

但是,现在我必须为同一个控件制作强烈的自定义助手。所以,我不必编写自定义绑定。

【问题讨论】:

    标签: asp.net-mvc razor html-helper


    【解决方案1】:

    如果没有自定义模型绑定器,就无法实现这一目标。这样做的原因是因为在您编写的自定义帮助程序中,下拉列表与特定名称(日、月和年)绑定,并且默认模型绑定器无法将这 3 个值绑定到单个 DateTime 实例。

    【讨论】:

    • 如果我删除名称并为每个下拉菜单使用 id 那么是否可以绑定它们。如果,是的,如何?如果没有,请详细说明你的答案。
    • 不,这是不可能的。 id 不用于绑定。只有输入字段的name 属性。这样做的原因是,当提交 HTML 表单时,浏览器使用输入字段的名称来准备将发送到服务器的 POST 请求。所以基本上 POST 正文有效负载将包含以下内容:Day=08&Month=04&Year=2013。现在您需要一个自定义模型绑定器来提取这些值并将它们打包到单个 DateTime 实例中。默认模型绑定器期望 POST 有效负载如下所示:SomeDateTimePropertyName=2013-04-08
    • 有没有其他方法可以实现双向绑定。(意思是如果我改变模型,用户界面就会受到影响,反之亦然)
    • 在这种情况下,自定义助手和模型绑定器是要走的路。
    • 如果我使用自定义助手和模型绑定器,那么当值来自数据库时如何填充下拉列表。
    猜你喜欢
    • 1970-01-01
    • 2013-02-14
    • 2015-10-20
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    相关资源
    最近更新 更多