1

I have a property of type "float" in my ViewModel. It's being displayed as a TextBox with a default value of "0".

I added an "EditorTemplates" folder inside the "Shared" folder & created a new "Float.cshtml" file with the following content:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue == 0 ? "" : ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line" })

However, still when I run the application, float fields are still being displayed with a default value of 0.

Thanks

UPDATE I am just trying to see how ASP.NET reacts to custom templates, till now, the engine is not processing my custom template, something similar to:

LatLng.cshtml

@model float
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line "}) Latitude

On the ViewModel,

    [UIHint("LatLng")]
    public float? Latitude { get; set; }

On the View,

@Html.EditorFor(model => model.Latitude)

Nothing is changing, default template is being used.

1
  • 1
    You don't show how you're adding the editor to your form/markup. Are you using Html.EditorFor()? Mar 30, 2012 at 17:44

2 Answers 2

5

Float is not actually a .NET type, it's a C# type. Float maps to System.Single, so you need to create a Single.cshtml and not a Float.cshtml.

You can also get around this by specifying a UIHint attribute on the model data, or by specifying the template to use in your Editor or EditorFor methods.

3
  • Is it normal when the Textbox shown on screen that it contains value 0? Also, Im very new to templates, what's the idea behind them, how to work with them? Thanks
    – Bill
    Mar 30, 2012 at 20:35
  • Yes, numeric textboxes always display a 0 by default. Templates are basically MVC's version of a user control, they allow you to create a custom display for any type you like. Mar 30, 2012 at 21:47
  • @bhaidar - If it contains a 0, it will display a 0. Yeah, it's normal that it displays whatever value is in the data item. Mar 31, 2012 at 0:29
0

An easy workaround is if you just set ViewData.TemplateInfo.FormattedModelValue to return a string in the model, so you don't have to do that weird logic on the view. If you need it to post back a new value (for editing purposes), you just have to add some logic in the controller to turn the string back into a float.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.