如何在MVC 3 Razor View Engine中使用C#显示和隐藏Div?
问题描述:
我必须编写用于在MVC3中显示和隐藏div的C#代码,用于基于C#中的开关大小写的各种控件。如何在不使用JQuery显示或隐藏的情况下完成显示或隐藏..但在完全服务器端..?如何在MVC 3 Razor View Engine中使用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有一篇关于Logic Conditions
使用此样本
@switch(value)
{
case "YourFistCase":
<div>Login</div>;
break;
case "YourSecondeCase":
<div>Logout</div>;
break;
}
或看到sample
// 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;
}
}
+0
是否有可能将所有这些代码移动到控制器...比在cshtml内联 – 2013-03-07 09:33:33
答
为什么使用switch语句?
你喜欢,如果条件?
为
<% if(CheckYourCondition){ %>
<div class="TestClass">
Test
</div>
<% } %>
+2
我相信OP要求使用Razor的解决方案... – jebar8 2013-03-07 05:02:11
Thnks,但我如何我得到的值是在控制器查看.. – 2013-03-07 05:17:35
会修改我的帖子给你看。 – Middas 2013-03-07 05:19:41
@vignesh,你也可以使用'ViewBag'或'ViewData'来将值从控制器传递到视图。 – 2013-03-07 05:25:20