【问题标题】:MVC Html Helpers - How much control over inbuilt ones?MVC Html Helpers - 对内置的有多少控制?
【发布时间】:2014-03-04 09:06:53
【问题描述】:

我对 ASP.NET MVC 框架中的 html 助手有一些疑问。所以...

  1. 我可以覆盖像 @Html.HiddenFor 这样的内置助手吗?
  2. 我应该override,还是创建一个CustomHiddenFor
  3. 在创建Custom 时,如何更改ModelMetaData 的值,然后调用内置助手?例如:

    public static MvcHtmlString HiddenSecuredFor<TModel, TProperty>
        (this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes,bool secured)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        var name = ExpressionHelper.GetExpressionText(expression);
        if (!secured)
        {
            return htmlHelper.HiddenFor(expression,htmlAttributes);
        }
    
            // Here I want to change the value 
            // from the TModel lets say the property is x => x.Name
            // And I want to make the Name = "Mr. " + Name
    
        // Call the inbuild helper with the expression value changes.
        return htmlHelper.HiddenFor(expression, htmlAttributes);
    }
    

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 html-helper


    【解决方案1】:
    1. 是 - How can I override the @Html.LabelFor template?
    2. 视情况而定 - 如果您要添加始终需要的功能,并且希望其他开发人员无需了解即可使用,那么覆盖是一个不错的选择。否则,创建一个调用原始的自定义是一个好方法。

    【讨论】:

    • 感谢您的回答和链接。但是 3. 呢?
    • 我不确定我是否完全理解您的意思,但元数据最终会转换为 htmlAttributes,因此如果您想添加自己的,可以将它们作为 htmlAttributes 传递。示例:pastebin.com/BbzPSkhN
    • htmlAttributes 很容易覆盖,但是如何从expression 更改实际值。在编写@Html.HiddenFor(x =&gt; x.Name) 时,我们有 1. 包含属性信息(名称、类型等)的表达式树。 2、@model MyNiceViewModel,其值为x =&gt; x.Name。如何更改该值?
    • 我不确定你是否可以这样做。我唯一的建议是自己构建整个结果,就像最初的例子一样。
    • 感谢您的建议。我会做一些实验。如果社区没有出现更好的解决方案(包括您的:)),我会将您的解决方案标记为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    相关资源
    最近更新 更多