MVC + Razor: how to add starting <div> conditionally?

时光毁灭记忆、已成空白 提交于 2020-01-15 05:19:04

问题


I want to amend a div based on whether a variable is set or not.

So I would like to do something like this:

@if (SomethingIsSet) {

<div style="background:red">

} else {

<div style="background:blue"> }

But I get the following error message in Visual Studio:

The div element was not closed. All elements must be either self-closing or have a matchig end tag.

My div element is closed later on in the page.


回答1:


You can use a ternary operator in Razor.

<div style="@(SomethingIsSet ? "background:red" : "background:blue")">



回答2:


You can use JavaScript. Just put id tag inside div: <div id="mydiv">


Then use JS:
var element = document.getElementById('mydiv');
if (something)
{
element.setAttribute('style','background-color: red;');
} else
{
element.setAttribute('style','background-color: blue;');
}


来源:https://stackoverflow.com/questions/54200264/mvc-razor-how-to-add-starting-div-conditionally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!