在不使用类的情况下为 Razor 中的 html 元素提供 id [英] Give id to html element inside Razor without using class

查看:52
本文介绍了在不使用类的情况下为 Razor 中的 html 元素提供 id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我遇到了错误.此页面上的另一个对象已使用 ID 'SpanID'.我想通过仅使用 ID(而不是使用类)来实现这一点,因为很多其他事情都依赖于此.

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.

推荐答案

声明一个变量并在你的范围内使用它.

Declare a variable and use that within your span.

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

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

正如 Alex 提到的,最好的方法是将此逻辑移至控制器并仅使用视图所需的数据填充 ViewModel.这也使您的代码更易于测试.

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.

这篇关于在不使用类的情况下为 Razor 中的 html 元素提供 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆