c# - How to create TagHelper who's value is a Model Property (without using @Model)? -


tag helper's 1 of sweet features of asp.net core. have created several tag helpers , can super helpful.

now try bit more advanced. tag helper attributes have ability created in such way attribute value model property.

and example of following:

 //model  public class mymodel{       public int myfield {get;set;} = 10;  }      //in view   @model mymodel    ...   <input asp-for="myfield" /> 

in above example asp-for tag helper input tag directed references property model. documentation says

the asp-for attribute value modelexpression , right hand side of lambda expression. therefore, asp-for="property1" becomes m => m.property1 in generated code why don't need prefix model.

so pretty cool, , same documentation appears call "expression name".

how create such property in own custom tag helper?

just declare parameter in taghelper of type modelexpression , use generate contents.

for example:

public class footaghelper : taghelper {     public modelexpression { get; set; }      public override void process(taghelpercontext context, taghelperoutput output)     {         output.tagname = "div";         output.content.sethtmlcontent( $@"you want value of property <strong>{for.name}</strong> <strong>{for.model}</strong>");     } } 

if use in view this:

@model testmodel  <foo for="id"></foo> <foo for="val"></foo> 

and pass model new testmodel { id = "123", val = "some value" } following output in view (formatted clarity):

<div>     want value of property <strong>id</strong>     <strong>123</strong> </div> <div>     want value of property <strong>val</strong>     <strong>some value</strong> </div> 

Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -