Reputation: 818
In Razor (MVC 4) can I do something like the following (pseudo)code?
<div id="One" @if(THIS_ID_IS("One")) {WRITE_SOMETHING_HERE} ></div>
<div id="Two" @if(THIS_ID_IS("One")) {WRITE_SOMETHING_HERE} ></div>
My intention is, that in DIV "One" an additional attribute will be written, but not in DIV "Two"
So, the THIS_ID_IS(string id) should determine, if the Razor-Parse is INSIDE the given DIV with id="xyz"
Is this possible?
Upvotes: 1
Views: 616
Reputation: 412
You can use single line if statement to overcome this situation
<div id="One" @(THIS_ID_IS("One") ? "write something" : "") ></div>
Upvotes: 1
Reputation: 586
As much as I would like it to be possible. It looks like it's not the case.
Based on these two articles :
It would seem that the Razor engine combines a code and a markup parser. The main parser decides to use one or the other. So the parsers are not aware of one another.
Simply put, in your example, <div id="One"></div>
and @if(THIS_ID_IS("One"))
would be parsed in different scopes and then just concatenated together.
Upvotes: 0
Reputation: 1433
In situations like this I tend to write a helper method to output the markup. This way you a not constrained by the 'rules' of razor. I did a similar thing to output jQuery slider html inside a div.
It also depends on your target audience, I rarely produce the actual views as our designer does most of that. I don't like handing over stuff to the 'creatives' that requires them to write/understand the logic.
It may not be the ideal solution or maybe even overkill in your situation but may be worth a look.
http://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs
Upvotes: 0
Reputation: 4288
Since ids
are unique
values. All divs will have diffrent ids.
So I dont think there is any need for Conditional Check in razor.
You can Directly add the extra attributes to your Div
as follows
<div id="One" attribute-name="Value"></div>
Upvotes: 0