在我的HTML文件中,我有一个必须禁用或启用的textbox,这取决于我的控制器值。将其设置为禁用模式没有问题,但要将其设置为启用...
这是我的代码:
<%= Html.TextBoxFor(model => model.test, new Dictionary<string, object> { { "disabled", ViewContext.RouteData.Values["controller"].ToString() == "MyTest" ? "" : "disabled"}}我在这个问题上看到了一些想法:here
对于我的问题,mvccontrib.FluentHtml或InputExtensions是唯一的解决方案?
我正在使用“禁用”,但我可以使用“只读”属性...这段代码的目的不是让用户填充文本框……
谢谢你在这个问题上的建议。
发布于 2011-04-01 00:07:59
只需将这行代码拆分成如下所示:
<%
if (MyConditionIsTrue)
Response.Write(Html.TextBoxFor(model => model.test, new { disabled = "true" }));
else
Response.Write(Html.TextBoxFor(model => model.test));
%>发布于 2011-04-01 00:39:39
这是定制HTML helper的一个很好的候选者:
public static class HtmlExtensions
{
public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex)
{
var controller = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
var htmlAttributes = new Dictionary<string, object>();
if (string.Equals(controller, "MyTest", StringComparison.OrdinalIgnoreCase))
{
htmlAttributes["disabled"] = "disabled";
}
return htmlHelper.TextBoxFor(ex, htmlAttributes);
}
}然后:
<%= Html.CustomTextBoxFor(model => model.test) %>发布于 2011-04-01 06:17:32
人们喜欢helpers,但是你没有来使用它们。
@if (MyConditionIsTrue) {
<input id="test" name="test" value="@Model.test" disabled="disabled" />
}
else {
<input id="test" name="test" value="@Model.test" />
}如果您必须多次重用此逻辑,则使用html helper可能是个好主意。如果你只做一次,可能就不是这样了。
https://stackoverflow.com/questions/5502686
复制相似问题