Html.TextBoxFor format and css class
Asked Answered
A

3

35

The two lines of code below work fine, but I want to combine them. What I mean is: I want to use the @class in the first code line. How can I do that?

<%: Html.TextBoxFor(model => model.Product.Price, String.Format("{0:f}", Model.Product.Price))%>

<%: Html.TextBoxFor(model => model.Product.Name, new { @class = "textBox150" })%>

thanks,

Filip

Archipenko answered 22/1, 2011 at 17:13 Comment(0)
M
75

I know I'm way late here but I just found a solution to this issue:

<%: Html.TextBoxFor(model => model.StartDate, new { @class = "datepicker", Value=String.Format("{0:d}", Model.StartDate) })%>
Mitinger answered 12/4, 2011 at 22:58 Comment(1)
@Mitinger - Thanks Man. This saved some hair on my head !Canales
C
0

I am afraid there is no clean way to achieve this. There are a couple of possibilities:

  1. Use an editor template for the Product property:

    <%: Html.EditorFor(x => x.Product) %>
    

    and inside this editor template:

    <%: Html.TextBox("Price", string.Format("{0:f}", Model.Product.Price), new { @class = "textBox150" }) %>
    <%: Html.TextBoxFor(model => model.Product.Name, new { @class = "textBox150" })%>        
    
  2. Write a custom helper that will append the class

  3. Wrap those textboxes in a span:

    <span class="container150">
        <%: Html.TextBoxFor(model => model.Product.Price, String.Format("{0:f}", Model.Product.Price))%>
        <%: Html.TextBoxFor(model => model.Product.Name)%>
    </span>
    

    and then modify your CSS rule:

    .container150 input {
        // some rule that applies to the textbox
    }
    
Counterpoison answered 23/1, 2011 at 9:9 Comment(0)
G
0

Again, it may be late, but I believe that much better solution is to use jquery.maskedinput plugin (also available as a nuget package).

Why is it better to use a plugin than just an input format? Well, when someone modifies an input, you will loose formating, if you don't use a plugin.

Here you can find a usage and a demo of how it works.

Godfather answered 23/8, 2012 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.