2013-03-07 65 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