EditorTemplate for "Floats" not being called in ASP.NET MVC 3 - asp.net-mvc-3

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.

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.

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.

Related

mvc3 is there a way to change the naming system of razor

I have a partial view that allows Html and the rendered name attribute of the <textarea> is throwing everything off, for instance this is my text area
#Html.TextAreaFor(model => model.cars.mycars)
causes the attribute to render as name="cars.mycars", is there anyway to change that to cars_mycars without using #Name ?
The reason why I want cars_mycars is because it is a field that has AllowHtml in it in the model
[AllowHtml]
public string mycars { get; set; }
In order for AllowHtml to work I would need a strongly typed model such as #Html.TextAreaFor(model => model.mycars) but I am using multiple models in 1 view therefore I have
#Html.TextAreaFor(model => model.cars.mycars, #new{id="cars_mycars",#Name="cars_mycars"})
This is all in a partialview and when I try to submit it nothing happens at all. That is the only field in the form so the issue much lie there and in addition if I put
ValidateInput(False)
on the action method then everything works fine which leads me back to the #name convention not working .
You can try like this
#Html.TextArea("cars_mycars")

how to bind model property to html helper textboxfor in mvc3

i want to tightly bind my property using html helper for TextBoxFor but i am not able to do so,i have simply binded using Textbox but i want to get data assign to textbox on httpPost
below is how i have done using simple HtmlHelper textbox
<%: Html.TextBox("RenewalDate", (string.Format("{0:yyyy/MM/dd}", Model.RenewalDate)), new { id = "txtRenewalDate", maxlength = 20, tabindex = 3, #class = "date" })%>
i dont want to use FormCollection that's why i want to bind tightly with TextBoxFor so that on httpPost my model has the value assigned to the Model.RenewalDate
please help....
Use an editor template, it's much easier:
<%= Html.EditorFor(x => x.RenewalDate) %>
and you could decorate your view model property with the DisplayFormat attribute to specify the desired format:
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime RenewalDate { get; set; }
and then your POST controller action will take the view model as action parameter.
[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
...
}
And in order to apply the HTML attributes such as class, tabindex and maxlength to this editor template you could write a custom metadata provider as shown in the following article.
Also since the date is using the yyyy/MM/dd it is possible that the default model binder is not able to parse the value back because the default model binder uses the current culture settings. To resolve this issue you could write a custom model binder as I showed in this thread.

MVC3 - 3 decimal places on type double with leading zero

I have a field for weight in Kgs (type double or use something else??).
In edit view I would like the user to enter numbers to the thousandth place.
In display view I would like the Kgs to appear like 560.250
Trying to learn MVC3 + Razor.
Willing to explore JQuery, use of regular expressions, validators, view templates, view models...
The "magic" of MVC based on conventions takes getting used to. Confused as to which approach to use.
Thank you in advance for your help.
You could use data annotations on your view model:
[DisplayFormat(DataFormatString = "{0:#,##0.000#}", ApplyFormatInEditMode = true)]
public double? Weight { get; set; }
and in your view
#Html.EditorFor(x => x.Weight)
will properly format the value in the input field.
Another possibility is to write a custom editor template for the double type (~/Views/Shared/EditorTemplates/double.cshtml):
#model double?
#Html.TextBox("", Model.HasValue ? Model.Value.ToString("#,##0.000#") : "")
and then in your view:
#Html.EditorFor(x => x.Weight)
or if you don't want to override all templates for all double types in your application you could put this into some custom template location like ~/Views/Shared/EditorTemplates/MyFormattedDouble.cshtml and then in your view:
#Html.EditorFor(x => x.Weight, "MyFormattedDouble")
Personally I prefer the first approach which uses data annotations to control the format of the double values.
To format the number just use
#string.Format("{0:0.00}", Model.Weight);
or
#Html.DisplayFor(x => string.Format("{0:0.00}", x.Weight));
#Html.EditorFor(x => string.Format("{0:0.00}", x.Weight));
to Validate
public class Model
{
[Required]
public double Weight{ get; set; }
}
I wouldn't constrain the precision they put in, just make sure that it is a valid number using javascript. You might also constrain input to only include numbers and a period.
If the user puts in something wrong (i.e. not compatible with a double type), MVC will complain when it tries to bind to the model.
its very simple
follow this method
so you have to insert DataFormatString="{0:#,##0.000#Kg}" only on gridview

ASP.NET MVC 3 Data Attributes - Programmatically Set UIHint from Controller

If i have a ViewModel like this:
public class SignupViewModel
{
[Required]
[DisplayName("Email:")]
public string EmailAddress { get; set; }
}
And use EditorFor to render out the form fields:
#Html.EditorFor(model => model.EmailAddress )
It will render <input type="text">. Cool.
But in this particular scenario, i have already retrieved Email from a different source, and i wish to pre-fill the form with this data, and show a label instead of a textbox (as i don't want them to change their email - don't worry about why).
I know i can use [UIHint], but can i do that programatically from the controller?
E.g:
var model = new SignupViewModel();
model.EmailAddress = GetFromMysterySource(); // How do i set a UIHint?
What's the best way to approach this? Should i use a seperate ViewModel altogether, which could mean changing my View from being strongly-typed to being dynamic, or should i not use EditorFor, or should i use a custom editor template?
Suggestions/advise would be greatly appreciated.
You can't apply an attribute at runtime. My suggestion would be to build a bit of logic into your view to control how the view renders the data. You may need to augment your model to indicate to the view which display to choose.
#if (Model.EmailAddressIsFixed)
{
#Html.DisplayFor( m => m.EmailAddress )
#Html.HiddenFor( m => m.EmailAddress ) // only if you need it to post back
}
else
{
#Html.EditorFor( m => m.EmailAddress )
}
If you are doing this in more than one place, then a custom editor template doing the same thing would probably be in order.
#Html.EditorFor( m => m.EmailAddress,
"FixedAddressTemplate",
new { Fixed = Model.EmailAddressIsFixed } )

ASP.Net MVC 3 EditorTemplate for DateTime Fields Error

This code was converted from some ASP.Net MVC 2 code in this tutorial:
MVC 2 Editor Template with DateTime
It is a custom EditorTemplate for DateTime fields stored as 'EditorTemplates/DateTime.cshtml'.
#Model DateTime?
#Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { #class = "datePicker" })
However I get the following error when using #Html.EditorFor(model => model.NewAbsence.StartDate):
CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'TextBox' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
I've seen some similar posts on here which mention casting the parameter of the EditorFor method, however I cannot seem to get this to work in my example.
Could someone please point out what I will need to change in my code. Thanks.
Actually it's #model with lowercase m:
#model DateTime?
^
instead of:
#Model DateTime?
So to sort of summarize what people are saying, and make it a bit more generic. If your view is declaring that it accepts dynamic models:
#model dynamic
Then things like extension methods will not be able to infer the types of arguments passed to them. Here are two examples (using Razor because it's awesome):
#Html.TextBox("myTextBoxName", Model.MyTextBoxValue)
#Html.DropDownList("myDropDownName", Model.MySelectList))
In these cases, the engine doesn't know what types Model.MyTextBoxValue or Model.MySelectList are, therefore it can't figure out what overloads of the extension methods to compile. So you just help it along with some strong typing:
#Html.TextBox("myTextBoxName", (string)Model.MyTextBoxValue)
#Html.DropDownList("myDropDownName", (SelectList)Model.MySelectList))
By the way, just to stop people from potentially pulling out their hair, that SelectList has to be properly instantiated with something like:
var items = List<SelectListItem>();
...
new SelectList(items, "Value", "Text");
As a temporary work around I am using:
<div class="editor-field date-field">
#Html.EditorFor(model => model.NewAbsence.StartDate)
#Html.ValidationMessageFor(model => model.NewAbsence.StartDate)
</div>
Then using the jQuery selector:
$(".date-field > input").datepicker({
showOn: "button",
buttonImage: "*pathtoimage*"
});
To apply the date picker to the input tags within the 'date-field' div. However this still doesn't format the date value how I want it to display initially, and cuts out the editor template entirely.
The error message comes from your textbox statement. In a template, this becomes a dynamic expression, and .Net doesn't know how to type the Model properties.
#Html.TextBox("", (string)(Model==null ? Model.Value.ToShortDateString() : string.Empty), new { style = "width: 10em;", #class="datefield" })
Explicitly cast your date value as string, and the dynamic expression has the information it needs. I also had a problem with the .HasValue property, but that wasn't the point of your question.

Resources