Give id to html element inside Razor without using

2019-07-21 23:06发布

问题:

@if (Model.Something != null)  
{ 
<span id="SpanID">Model.SomethingElse</span> 
}  
else  
{
<span id="SpanID">Model.SomethingElse2</span>
}

I am getting error. Another object on this page already uses ID 'SpanID'. I want to accomplish this by using ID only(and not using class) because lots of other things depend on that.

回答1:

Declare a variable and use that within your span.

@{
    var result = Model.Something != null ? 
        Model.SomethingElse : Model.SomethingElse2;
}

<span id="SpanID">@result</span>

As Alex mentioned the best way is to move this logic to the controller and populate a ViewModel with only the data required for the view. This also makes more of your code testable.



回答2:

You could rewrite it:

@{
    if (Model.Something != null) {
        ViewData["whatever"] = Model.SomethingElse;
    }
    else {
        ViewData["whatever"] = Model.SomethingElse2;
    }
}

<span id="SpanID">@ViewData["whatever"]</span> 

Or use a ViewModel, moving the check from the View to the Controller (where it belongs, methinks).



标签: razor