2013-03-07 53 views

回答

11

将您的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> 
+0

Thnks,但我如何我得到的值是在控制器查看.. – 2013-03-07 05:17:35

+0

会修改我的帖子给你看。 – Middas 2013-03-07 05:19:41

+1

@vignesh,你也可以使用'ViewBag'或'ViewData'来将值从控制器传递到视图。 – 2013-03-07 05:25:20

0

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

-2

为什么使用switch语句?

你喜欢,如果条件?

<% if(CheckYourCondition){ %> 

    <div class="TestClass"> 
    Test 
    </div> 

<% } %> 
+2

我相信OP要求使用Razor的解决方案... – jebar8 2013-03-07 05:02:11