如何在MVC 3 Razor视图引擎中使用c#显示和隐藏Div

本文关键字:显示 Div 隐藏 引擎 MVC 视图 Razor | 更新日期: 2023-09-27 18:02:45

我必须在c#中编写c#代码来显示和隐藏MVC3中基于c#切换情况的各种控件的div。如何在不使用JQuery的情况下完成显示或隐藏…但是在完全的服务器端…?

如何在MVC 3 Razor视图引擎中使用c#显示和隐藏Div

将switch语句直接添加到.cshtml文件中。此时,它将全部位于服务器端。

控制器:

public ActionResult Page()
{
    string data = "value1";
    return View(data);
}

CSHTML:

@model string; // this should be the Type your controller passes
<div>some html content</div>
@switch(Model) // Model is how you access your passed data
{
    case "value1":
        <div>...</div>
    break;
    case "value2":
        <div>...</div>
    break;
}
<div>more html content</div>

W3c有一篇关于逻辑条件的文章

使用这个示例

@switch(value)
{
    case "YourFistCase":
        <div>Login</div>;
    break;
    case "YourSecondeCase":
        <div>Logout</div>;
    break;
}

或参见示例

// Use the @{ } block and put all of your code in it
@{
    switch(id)
    {
        case "test":
            // Use the text block below to separate html elements from code
            <text>
                <h1>Test Site</h1>
            </text>
            break;  // Always break each case
        case "prod":
            <text>
                <h1>Prod Site</h1>
            </text>
            break;
        default:
            <text>
                <h1>WTF Site</h1>
            </text>
            break;                   
    }
}

为什么使用switch语句??

你喜欢这个条件吗??

<% if(CheckYourCondition){ %>
   <div class="TestClass">
   Test
   </div>
<% } %>