ASP.NET MVC - 扩展TextBoxFor无需重新编写方法 [英] ASP.NET MVC - Extending TextBoxFor without re-writing the method
问题描述
是否有任何可能的方式来扩展基本的HTML佣工( TextBoxFor
, TextAreaFor
等)使用扩展方法他们的产出,而不是仅仅重写整个方法完全?例如,添加在...
Is there any possible way to extend the basic html helpers (TextBoxFor
, TextAreaFor
, etc) using extension methods on their output, instead of just re-writing the entire methods completely? For instance, adding in ...
@ Html.TextBoxFor(型号=> model.Name).Identity(idName)
我知道我可以用这个实现以下,已经..
I know I can achieve this using the following, already..
@ Html.TextBoxFor(型号=> model.Name,新{@id =idName})
不过,获取笨重和令人沮丧的管理时,你必须开始添加很多的属性。有什么办法来添加扩展到这些固有的不只是 htmlAttributes
通过为每个小细节?
But that gets clunky and frustrating to manage when you have to start adding a lot of properties. Is there any way to add extensions to these inherently without just passing in htmlAttributes
for every little detail?
推荐答案
由于@AaronShockley说,因为 TextBoxFor()
返回 MvcHtmlString
,你开发修改输出的流体API式唯一的选择将是通过辅助方法 MvcHtmlString
返回s运行。这样做,我认为一个稍微不同的方式接近你以后会使用属性生成器的对象,像这样的:
As @AaronShockley says, because TextBoxFor()
returns an MvcHtmlString
, your only option for developing a 'fluid API' style of amending the output would be to operate on the MvcHtmlString
s returned by the helper methods. A slightly different way of doing this which I think approaches what you're after would be to use a 'property builder' object, like this:
public class MvcInputBuilder
{
public int Id { get; set; }
public string Class { get; set; }
}
...并设置扩展方法是这样的:
...and to set up extension methods like this:
public static MvcHtmlString TextBoxFor<TModel, TProp>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProp>> expression,
params Action<MvcInputBuilder>[] propertySetters)
{
MvcInputBuilder builder = new MvcInputBuilder();
foreach (var propertySetter in propertySetters)
{
propertySetter.Invoke(builder);
}
var properties = new RouteValueDictionary(builder)
.Select(kvp => kvp)
.Where(kvp => kvp.Value != null)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
return htmlHelper.TextBoxFor(expression, properties);
}
然后,您可以做这样的东西在你查看:
You can then do stuff like this in your View:
@this.Html.TextBoxFor(
model => model.Name,
p => p.Id = 7,
p => p.Class = "my-class")
这让你输入的属性,你可以通过添加属性到合适的子类MvcInputBuilder自定义每个扩展方法强类型和智能。
This gives you strong typing and intellisense for input properties, which you could customise for each extension method by adding properties to an appropriate MvcInputBuilder subclass.
这篇关于ASP.NET MVC - 扩展TextBoxFor无需重新编写方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!