Reputation: 7174
I have an MVC 3 application which should allow the user to display and edit values of different types. The view responsible for doing this does not neccessarily know about the type of the value (it is declared as object), but I want it to render the correct editor template. Right now I have this:
<%: Html.EditorFor(n => attribute.ValueTyped) %>
attribute.ValueTyped is of type object. When ValueTyped is of type bool, MVC renders a check box (which is what it is supposed to do). However, as soon as ValueTyped is of a different type (so far I've tried int, double, string), MVC does not render anything at all.
How do I make MVC render the generic templates for int, double, string or whatever type my ValueTyped contains? Please note: I do not want to generate the text boxes myself, but I'd rather let MVC decide which editor template to use.
Upvotes: 0
Views: 926
Reputation: 9488
You could try to pass the name of the editor template explicitly by passing it as the second argument. Based on your dynamic situation this could look like the following:
<%: Html.EditorFor(m => attr.ValueTyped, attr.ValueTyped.GetType().Name) %>
Of course, your question is quite old - maybe you could update it with the answer you found?
Upvotes: 1
Reputation: 21
When setting up an MVC 3 application, the foreign keys that should allow drop down lists to select an item do not get rendered as drop downs, but as static inputs. This can be resolved by creating a custom display and view for that field. We will need to start by creating a custom partial view that will live in “~/Views/Shared/DisplayTemplates/UserGuid.cshtml”, and “~/Views/Shared/EditTemplates/UserGuid.cshtml”. The code for one is located below:
@model Guid
@{
incMvcSite.Models.MvcSiteDB db = new incMvcSite.Models.MvcSiteDB();
incMvcSite.Models.SecUser usr = db.SecUsers.Single(u => u.Guid == Model);
}
@usr.Display
This is a display for template that will look up the item in the referenced table and display it. We also need an edit for template as follows:
@model Guid
@{
incMvcSite.Models.MvcSiteDB db = new incMvcSite.Models.MvcSiteDB();
SelectList items = new SelectList(db.SecUsers.OrderBy(i => i.Display).ToList(), "Guid", "Display", Model);
}
@Html.DropDownList("", items)
The edit for template is implemented as a drop down list. Originally, we has used static HTML code, but the problem will appear of implementing a “prefix”. Static HTML code does get handled by HTML helpers, so it’s recommended that you use the HTML.DropDownList(). To force the MVC framework to use the new Display and Edit for templates, we need to annote our model item an add the following line: [UIHint("UserGuid")]
This will cause MVC to use the Display and Edit templates named “UserGuid”, which are just partial views.
Upvotes: 1