I have a question about Editor Templates. For example I have a model with date field, product prize field and weight of product field. I have successfully created Editor Templates for DateTime and Decimal. I'm given to understand that when I use EditorFor for any field it takes template depending on a data type of the field.
So when I use: EditorFor(m=>m.DateOfBirth) which is DateTime format it looks for DateTime template in EditorTemplates folder and EditorFor(m=>m.ProductPrice) which is double it looks for Double template, etc.)
Question is how can I differ that I want to use one Decimal template with string format ##0.00 for (double)ProductPrize and another template with format ##0.0000 for (double)ProductWeight?
Any help would be appreciated
You may want to use an overload of EditorFor, which accepts template name as second parameter, like:
EditorFor(m=>m.ProductPrice, "PriceEditorTemplate")
More info: MSDN
Define it in your model using the UIHint attribute:
[UIHint("MySpecificEditorTemplate")]
public ProductPrice {get;set;}
And EditorFor will use the MySpecificEditorTemplate.cshtml for example.
Related
Is it possible to create a custom version of the UIHint attribute?
When my company first adopted MVC, we used a lot of Html.* helper methods. We are in the process of redesigning out MVC template to make use of the full power of MVC. One way we are doing this is with Display and Editor Templates.
However, one popular HTML extension method we had was to generate dropdowns for Enums. One of the options we had was to sort by the int value or the description or text of the EnumMember.
I would like to see about creating a EnumDropdown attribute that accepts several parameters that can customize the output of the HTML dropdown. However, I don't think it's possible to do this while still retaining the benefits of the UIHint attribute. Meaning, that I won't be able to simply call #Html.EditorFor(m => Model)
I had found that there is a System.Web.UI.IAutoFieldGenerator interface but it doesn't appear to do what I want. Any suggestions?
The newer versions of MVC have this built in now:
EnumDropDownListFor HTML Helper
The only thing UIHint does is suggest a Display or Editor template name. MVC will then add this name to the search path when looking for that template.
You can just use UIHint as is and have your generator create these for you in the correct folders and not have to customize it.
this question I got from some tests:
Which of the following templated HTML helpers of MVC bypasses all
templates and renders a simple string representation of the specified
model property?
and options:
Display
Label
DisplayText
Editor
as I understand, it means, that which helper displays property as string? The correct answer is Label?
the correct answer is DisplayText and don't get confused with DisplayTextFor which is a strongly typed version of DisplayText and returns the annotation value of your model attribute (if predefined) or null otherwise
I have the following model class which contains a bool value:-
Public class Server
{
public bool IsIPUnique { get; set; }
}
Currently i am using the following to display the check box inside my Razor view:-
<input type="CheckBox" name="IsIPUnique" value="true" #(Html.Raw(Model.IsIPUnique ? "checked=\"checked\"" : ""))/> IP Unique.
but i read about the EditorFor template, and it can automatically create the check box and check/uncheck it based on the model values so i tried the following :-
#Html.EditorFor(model=>model.IsIPUnique)<span>test</span>
so my question is if i can replace my old code with the new one that uses the EditorFor ?, or asp.net mvc might deal with these values differently ?
Thanks
Basically you have 3 possibilities:
Write HTML manually (as you have done)
I would avoid writing the HTML manually if there is a HTML helper available.
Manually written HTML is prone to errors which can cause problems with model binding.
Use the specific HTML helpers (Html.CheckBoxFor)
The specific HTML helpers add a layer of abstraction to all controls.
It's easy to modify the template of all controls that use the same HTML helper and it makes your views more readable.
Use the general EditorFor
The EditorFor HTML helper is great if your model datatypes change often.
The EditorFor will adjust the input fields automatically to the new datatype and won't throw an error (as with the specific HTML helpers).
It is also a bit harder to add HTML attributes to the EditorFor while the specific HTML helpers often have overloads for them.
However, this is fixed in MVC 5.1: http://weblogs.asp.net/jongalloway/looking-at-asp-net-mvc-5-1-and-web-api-2-1-part-3-bootstrap-and-javascript-enhancements
Conclusion: in your case I would use the CheckBoxFor HTML helper because the datatype won't change likely and it will make the view cleaner
I'm upgrading an MVC3 application to MVC4 using the instructions from Microsoft. Everything went fairly smoothly - except a few of my date model properties are now rendering differently. For example, one of these properties is defined in the viewmodel like this:
[Required(ErrorMessage = "Required")]
[DataType(DataType.Date)]
[RegularExpression(#"([1-9]|0[1-9]|1[012])...",
ErrorMessage = "Format is mm/dd/yyyy")]
[FormatHint("mm/dd/yyyy")]
[InputSize("small")]
public string Date { get; set; }
Before upgrading to MVC4, this would be rendered via calling #Html.EditorFor(m => m.Date) which would use a custom EditorTemplate - the String.cshtml template (since it's a string!). I have some custom data annotations that formats the html so it utilizes a field layout, jQueryUI, and twitter Bootstrap on the client side. The validation is done via jquery validation unobtrusive. Anyhow, this is how it previously rendered:
Now that I'm using MVC4, the String.cshtml editor template is not being called for this property any longer. It renders like this (in Chrome using the HTML5 editor stuff, I assume):
The input element looks pretty much the same - all the jQuery validation bits are in there - the only difference seems to be the type attribute is now type="date", where before it was type="text".
I'd like to continue using the String.cshtml EditorTemplate for this datatype. I'm thinking there might be a data annotation that I can put on the ViewModel property to provide a TemplateHint for #Html.EditorFor(...). If not this, I'd like to know the custom EditorTemplate that I can write to hijack MVC4's formatting (I've already tried DateTime.cshtml - it's not being called either). If not either of those, then I'm open to suggestions on how to get my property rendering like it used to.
In MVC4, the used template is determinated from :
The UIHintAttribute if any
The DataTypeAttribute if any
The type of the property
In MVC3, the DataTypeAttribute was not used.
Your property has a
[DataType(DataType.Date)]
so the template Date.cshtml is used. If it does not exists, default rendering is executed.
You have two options to resolve your problem :
Add a UIHint("String") on your property, or
Rename your editor template from String.cshtml to Date.cshtml
I have a date time picker combination in a edit template that can be used like Html.EditorFor(x => x.ETA) but now I want to use the same template somewhere where I don't have a model that contains a DateTime property. So I tried Html.Editor("DateWithTime", "Arrival") which uses the correct template, but doesn't assign a value to ViewData.ModelMetadata.PropertyName which is something that my template relies on. It sets the id of the textbox which is obviously important.
Is there a way to render the template and assign a id value to the ViewData.ModelMetadata.PropertyName so I can re-use the logic in the template instead of having to copy it?
Maybe use ViewData.TemplateInfo.HtmlFieldPrefix instead of ViewData.ModelMetadata.PropertyName.
I am not sure but I thought that HtmlFieldPrefix an PropertyName have the same value as long as you do not iterate a collection.
You can modify the HtmlFieldPrefix property with the htmlFieldName parameter from Html.Editor.
You can use the UIHint in your model. give it the name of the template you want to use
[UIHint("DateWithTime")]
You still use EditorFor with this.