asp.net mvc 4 - Custom helpers setting element attributes equal to a model property -


using mvc 4.5 custom html helper, how can set custom element's id model's property.

i have created 2 classes:

public class zclass1 {     public zclass2 zclass2 { get; set; } }  public class zclass2 {     public string name { get; set; } } 

within view model

@model zclass1 

i have created simple custom html helper:

using system; using system.web.mvc;  namespace j6.salesorder.web.models.helpers {     public static class spanextensions     {         public static mvchtmlstring span(this htmlhelper helper, string id, string text)         {             var tagbuilder = new tagbuilder("span");             tagbuilder.attributes.add("id", id);              return new mvchtmlstring(tagbuilder.tostring());         }     } } 

so, within view html helper used:

@using mymodelpath.models.helpers  @html.span("myid","just text"); 

it renders correctly:

<span id="myid">just text</span> 

however, instead of hard coding id, take advantage of using model, rendered output be:

<span id="zclass2.name">just text</span> 

any ideas appreciated.

thank you.

there's new htmlhelper.idfor(...) method, use one...

public static mvchtmlstring span<tmodel, tproperty>(this htmlhelper<tmodel> helper, expression<func<tmodel, tproperty>> expression, string text) {     var tagbuilder = new tagbuilder("span");     var id = helper.idfor(expression);     tagbuilder.attributes.add("id", id.tostring());      return new mvchtmlstring(tagbuilder.tostring()); } 

usage

@html.span(m => m.zclass2.name, "just text") 

this won't render zclass1.zclass2, usual id renderers htmlhelpers extension method.


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -