我想根据我传递的特定属性及其值来生成。这就是我想要使用助手的方式:
<sometag @PossibleHelper(parameter)/>
PossibleHelper 完成他的工作后,结果可能是这样的:
<sometag attributeName="attributeValue"/>
我如何在助手中表达这一点?
@helper PossibleHelper(someType){
if(condition){
attributeName="attributeValue" //this is wrong
}
}
最佳答案
当您使用助手时,这只是常规的 razor 语法。
@helper PossibleHelper(SomeType something) {
if (condition) {
<span attributeName="attributeValue">blah</span>
}
}
您可以设置这样的属性。
@helper PossibleHelper(int something) {
var attrValue = string.Empty;
if (true) {
attrValue = "attributeValue";
}
@(string.Format("attribute={0}", attrValue))
}
用法:
<sometag @PossibleHelper(parameter)/>
仅供引用,您还可以为 HtmlHelper
创建一个扩展方法,如果代码在 View 之间共享或有相当多的逻辑,这可能会更好。
public static class HtmlHelperExtensions
{
public static MvcHtmlString SomeExtension(this HtmlHelper htmlHelper)
{
// ...
}
}
关于c# - 是否可以将 HTMLHelper 不仅用于属性值,还可以用于属性名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15102696/