Rod
Rod

Reputation: 15457

binding inside html helper

i want to bind to the display style property of my Html.TextBox

<%= Html.TextBox("RunDates", Model.RunDates, new { style = "display: none" })%>

is this possible? i want to do something like the following that i know works for me:

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

or is there a way to post <input type="text" ... in mvc?

Upvotes: 0

Views: 400

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You could write a custom Html helper for this. There are 2 possibilities:

  1. You replace this weakly typed TextBox helper with strongly typed TextBoxFor by taking advantage of a view model (which is what I would recommend) in which case you will be able to write your textbox like this:

    <%= Html.MyTextBoxFor(x => x.RunDates) %>
    
  2. You stick with weak typing in which case the best you could get is this:

    <%= Html.TextBox("RunDates", Model.RunDates, Html.SelectStyle(Model.IsEnabledProductSetupBack)) %>
    

Now since I recommend the first solution, it is the one I would provide same code for:

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);
    }
}

Upvotes: 1

Related Questions