Give id to html element inside Razor without using

2019-07-21 23:10发布

@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.

标签: razor
2条回答
虎瘦雄心在
2楼-- · 2019-07-21 23:26

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.

查看更多
再贱就再见
3楼-- · 2019-07-21 23:36

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).

查看更多
登录 后发表回答