2011-01-13 83 views
1

我想修改佣工像这样的:修改HTML佣工在ASP.NET MVC 2

<%= Html.CheckBoxFor(m => m.Current, new { @class = "economicTextBox", propertyName = "Current", onchange = "UseCurrent();UpdateField(this);" })%> 

也采取作为一个参数,它标志着一个应用程序的权限,然后里面的另一个字符串方法我会决定是否返回实际的HTML或什么也不做,这取决于他们的许可。

我该怎么做?

更新2:当我调试和检查htmlHelper.CheckBoxFor(表达,mergedHtmlAttributes)的值._值复选框不渲染为只读

,我得到这个

<input checked="checked" class="economicTextBox" id="Current" name="Current" onchange="UseCurrent();UpdateField(this);" propertyName="Current" readonly="true" type="checkbox" value="true" /><input name="Current" type="hidden" value="false" /> 

但该复选框仍渲染允许我改变它并实现全部功能。为什么?

回答

3

你可以写一个自定义的助手:

public static MvcHtmlString MyCheckBoxFor<TModel>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, bool>> expression, 
    string permission, 
    object htmlAttributes 
) 
{ 
    if (permission == "foo bar") 
    { 
     // the user has the foo bar permission => render the checkbox 
     return htmlHelper.CheckBoxFor(expression, htmlAttributes); 
    } 
    // the user has no permission => render empty string 
    return MvcHtmlString.Empty; 
} 

然后:

<%= Html.CheckBoxFor(
    m => m.Current, 
    "some permission string", 
    new { 
     @class = "economicTextBox", 
     propertyName = "Current", 
     onchange = "UseCurrent();UpdateField(this);" 
    }) 
%> 

UPDATE:

这里的,这样它呈现一个你可以如何修改HTML帮助只读复选框而不是空字符串,如果用户没有权限:

public static MvcHtmlString MyCheckBoxFor<TModel>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, bool>> expression, 
    string permission, 
    object htmlAttributes 
) 
{ 
    if (permission == "foo bar") 
    { 
     // the user has the foo bar permission => render the checkbox 
     return htmlHelper.CheckBoxFor(expression, htmlAttributes); 
    } 
    // the user has no permission => render a readonly checkbox 
    var mergedHtmlAttributes = new RouteValueDictionary(htmlAttributes); 
    mergedHtmlAttributes["readonly"] = "readonly"; 
    return htmlHelper.CheckBoxFor(expression, mergedHtmlAttributes); 
} 
+0

这完全是我想要的。但我会在哪里放置这种方法?在某个额外的类中,然后在aspx视图中引用命名空间? – slandau 2011-01-13 15:22:56

2

为了做你想做的事情,你需要创建你自己的HTML Helper。 HTML Helper方法只是扩展方法。因此,您可以轻松创建自己的代码,进行适当的权限检查,然后如果它通过,请使用其余参数调用默认的Html.CheckBoxFor。

这个以前的question有一个体面的创建自定义助手的例子。

+0

......这是有道理的。有点。所以,例如,我会创建的方法在哪里?我怎么从视图中调用它?然后,我将如何从该方法调用HTML助手? – slandau 2011-01-13 15:20:38