asp.net mvc - Razor, shortest conditional block -


i use code like:

<p @if(model.sth) {     ?:style="display: none;" }>some text</p> 

many template engines have special markers conditional blocks, example in mustache can write:

<p {{#model.sth}}style="display: none;"{{/model.sth}}>some text</p> 

can razor code can written in shorter form?

in razor can embed expressions inside parenthesis execute them inline. if conditional can written using ternary operator, can this:

@(this.model.sth ? "style='display:none;'" : string.empty) 

the trick getting razor emit resulting string correctly html. use htmlhelper it, gets messy enough long-form conditional cleaner.

in specific case of attribute, however, there's special feature of razor, of mvc4, help. if specify attribute using expression evaluates null, mvc won't emit attribute @ all, can do:

<p style="@(this.model.sth ? "display:none;" : null)">some text</p> 

(note null , string.empty different in case: razor emit style="" if expression evaluates empty string.)


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -