2012-07-06 49 views
0

我已經從控制器傳遞來自控制器的CSS類在asp.net MVC3的局部視圖

public ActionResult CreatePage() { 

    return PartialView("APage"); 
} 

一個簡單的代碼和該網頁APage的部分是:

<table class="@className"> 
    <tr> 
    ... 
    </tr> 
</table> 

在JavaScript的,我想生成APage與不同的類名稱(css類名稱)

$.post('CreatePage', function(data) { 
    $('.result').html(data); 
}); 

如何要傳入控制器功能(如果我聲明:public ActionResult CreatePage(string cssClass) { ... })參數爲PartialView函數?

手段

我要像:

public ActionResult CreatePage(string cssClass) { 

     return PartialView("APage", cssClass); 
    } 

而且我想使用CSS類爲APage視圖。

例如:

  1. 如果我打電話

    $.post('CreatePage', {cssClass: 'aClass' ,function(data) { $('.result').html(data); });

  2. 然後,它會調用

    public ActionResult CreatePage(string cssClass) { 
    
        return PartialView("APage", cssClass); //cssClass = 'aClass' 
    } 
    
  3. ,並返回視圖像

    <table class="aClass"> <tr> ... </tr> </table>

謝謝

+0

你爲什麼不改變與JavaScript客戶端的類名? – nemesv 2012-07-06 06:47:13

+0

爲什麼你想改變班級名稱?以及你認爲你有多少個CSS類,如果很少你可以在視圖中放置一個簡單的邏輯 – Elham 2012-07-06 07:43:47

+0

什麼是你的視圖引擎? – Elham 2012-07-06 07:44:43

回答

0

我不知道如果我理解正確的,你的,但你的例子,我想,已經是在正確的軌道上。

在您的局部視圖,在最高層補充一點:

@model string 

,然後在局部視圖,table標籤定義修改爲

<table class="@Model"> <tr> ... </tr> </table> 
+0

我知道,但我已經有一個比'string'類型的其他類型 – 2012-07-06 06:54:42

+0

然後修改你的模型以包含cssClass。如果此時不存在,則創建一個'ViewModel'。然後從你的控制器動作構造ViewModel,然後將ViewModel傳遞給你的局部視圖。在您的部分視圖中,將@model聲明更改爲ViewModel的類型。 – rikitikitik 2012-07-06 06:56:52

0

要在什麼@rikitikitik說延長。

您已經發現PartialView(viewName, model)方法過載,現在您只需要擴展當前的model即可包含CSS類字符串。只需添加一個名爲CssClass的屬性,您就可以在局部視圖中使用它。

這當然假設您使用的是view models(以及因此MVVM pattern),而不是「just」模型甚至是數據庫模型(例如由Entity Framework處理)。

public class APartialModel 
{ 
    public string Name { get; set; } 
    // ... other properties 
    public string CssClass { get; set; } 
} 
public ActionResult CreatePage(string cssClass) { 

    // Initialize the entire view model for the partial view here 
    // This usually means you need to pass in an id and use it to 
    // make a database lookup. 
    // If it's "too much work", it probably means you 
    // need to fix a structural problem. 
    APartialModel model = new APartialModel 
     { 
      Name = "Somehow I already know this value", 
      CssClass = cssClass 
     }; 

    return PartialView("APage", model); 
} 
@model APartialModel 

<table class="@Model.CssClass"> 
    <tr> 
    ... for example @Model.Name 
    </tr> 
</table> 
相關問題