c# - ASP.NET MVC 2 - Html.EditorFor a nullable type? -


i have 2 editor templates: 1 decimal, , 1 decimal? (nullable)

but when have nullable decimal in model, tries load normal decimal editor:

<%: html.editorfor(model => model.somedecimal )%> <%: html.editorfor(model => model.somenullabledecimal )%> 

the first 1 works fine, , loads decimal editor template. second 1 tries load decimal template (and fails because not decimal field).

the error message is:

the model item passed dictionary null, dictionary requires  non-null model item of type 'system.decimal'.  

my templates declared this:

decimal template:

<%@ control language="c#"  inherits="system.web.mvc.viewusercontrol<system.decimal>" %> 

nullable decimal template:

<%@ control language="c#"  inherits="system.web.mvc.viewusercontrol<system.decimal?>" %> 

i know can make work passing in template name, eg

but prefer work automatically using type other templates.

<%: html.editorfor(model => model.somenullabledecimal,  "nullabledecimaltemplate" )%> 

thanks bryan adding bounty try positive solution, i'm going have answer , have found answer no - cannot have nullable template auto-discovered type. must use template name.

this relevant quote brad wilson's blog @ http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html. authoritative source on mvc have believe him when says:

when searching type name, simple name used (i.e., type.name) without namespace. also, if type nullable, search t (so you’ll boolean template whether you’re using “bool” or “nullable”)

he goes on say

this means if you’re writing templates value types, need account whether value nullable or not. can use isnullablevaluetype property of modelmetadata determine if value nullable. we’ll see example of below built-in boolean template.

so yes there answer question, unfortunately answer no.

to use nullable template must explictly use template name:

<%: html.editorfor(model => model.somenullabledecimal, "nullabledecimaltemplate" )%> 

or can use 1 template handle both nullable , non nullable type:

<% if (viewdata.modelmetadata.isnullablevaluetype) { %>     <%= html.dropdownlist("", tristatevalues, new { @class = "list-box tri-state" })%> <% } else { %>     <%= html.checkbox("", value ?? false, new { @class = "check-box" })%> <% } %> 

Comments

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

c++ - How do I get a multi line tooltip in MFC -

unit testing - How to mock PreferenceManager in Android? -