asp.net mvc - Making my own HtmlHelper extension for input that works with model binding -


i unhappy current dropdownlist implementation, because can't option tags (only selected, text , value supported). want make own can set disabled , other stuff on individual options.

currently i'm altering options javascript, think it's bit of hacky way it, , i'd prefer render correct html begin with.

i know can make template uses select , option tags , make options want them - normal dropdownlist extension adds stuff val stuff , specific name , id guess proper databinding when submitting form:

<select data-val="true" data-val-number="the field selectedvalue must number." id="parentdropdown_selectedvalue" name="parentdropdown.selectedvalue"> 

how go adding these attributes own templates?

you right, attributes (and specially name attribute) critical model binding.

say want create custom helper like

public static mvchtmlstring customhelperfor<tmodel, tvalue>(this htmlhelper<tmodel> html, expression<func<tmodel, tvalue>> expression) 

first can use var fieldname = expressionhelper.getexpressiontext(expression); field name.

then use var fullbindingname = html.viewcontext.viewdata.templateinfo.getfullhtmlfieldname(fieldname); in order full name, taking care of nested views.

finally can transform id attribute using var fieldid = tagbuilder.createsanitizedid(fullbindingname);.

so simple custom helper creates textbox written as:

public static mvchtmlstring customhelperfor<tmodel, tvalue>(this htmlhelper<tmodel> html, expression<func<tmodel, tvalue>> expression) {                 var fieldname = expressionhelper.getexpressiontext(expression);     var fullbindingname = html.viewcontext.viewdata.templateinfo.getfullhtmlfieldname(fieldname);     var fieldid = tagbuilder.createsanitizedid(fullbindingname);      var metadata = modelmetadata.fromlambdaexpression(expression, html.viewdata);     var value = metadata.model;      tagbuilder tag = new tagbuilder("input");     tag.attributes.add("name", fullbindingname);     tag.attributes.add("id", fieldid);     tag.attributes.add("type", "text");     tag.attributes.add("value", value == null ? "" : value.tostring());      var validationattributes = html.getunobtrusivevalidationattributes(fullbindingname, metadata);     foreach (var key in validationattributes.keys)     {         tag.attributes.add(key, validationattributes[key].tostring());     }      return new mvchtmlstring(tag.tostring(tagrendermode.selfclosing)); } 

you can use in view like:

@html.customhelperfor(model => model.parentdropdown.selectedvalue) 

and produce following html:

<input id="parentdropdown_selectedvalue" name="parentdropdown.selectedvalue" type="text" value="4"> 

hope helps!


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -