绑定在html帮助器中

时间:2011-10-18 18:53:08

标签: asp.net-mvc

我想绑定到我的Html.TextBox

的显示样式属性
<%= Html.TextBox("RunDates", Model.RunDates, new { style = "display: none" })%>
这可能吗?我想做以下事情,我知道这对我有用:

<input id="btnBack" class="btnAction" type="button" value="Back" style="display: <%= Model.IsEnabledProductSetupBack?"inline":"none" %>;" />

或者有没有办法在mvc中发布<input type="text" ...

1 个答案:

答案 0 :(得分:1)

您可以为此编写自定义Html帮助程序。有两种可能性:

  1. 您可以利用视图模型(这是我推荐的)替换这个弱类型的TextBox助手与强类型的TextBoxFor,在这种情况下,您将能够像这样编写文本框:

    <%= Html.MyTextBoxFor(x => x.RunDates) %>
    
  2. 你坚持使用弱打字,在这种情况下你能得到的最好是:

    <%= Html.TextBox("RunDates", Model.RunDates, Html.SelectStyle(Model.IsEnabledProductSetupBack)) %>
    
  3. 现在,因为我推荐第一个解决方案,我将提供相同的代码:

    public static class HtmlExtensions
    {
        public static IHtmlString MyTextBoxFor<TProperty>(
            this HtmlHelper<MyViewModel> helper, 
            Expression<Func<MyViewModel, TProperty>> ex
        )
        {
            var model = helper.ViewData.Model;
            var htmlAttributes = new RouteValueDictionary();
            htmlAttributes["style"] = "display: none;";
            if (model.IsEnabledProductSetupBack)
            {
                htmlAttributes["style"] = "display: inline;";
            }
            return helper.TextBoxFor(ex, htmlAttributes);
        }
    }