簡體   English   中英

將CSS類從控制器傳遞到ASP.NET MVC3中的局部視圖

[英]Pass a css class from controller to a partial view in asp.net mvc3

我有一個來自控制器的簡單代碼

public ActionResult CreatePage() {

   return PartialView( "APage" );
}

該頁面APage的一部分是:

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

在javascript中,我要生成具有不同類名(css類名)的APage

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

如何將控制器函數(如果我要聲明: public ActionResult CreatePage(string cssClass) { ... } )傳遞給PartialView函數?

手段

我想要:

public ActionResult CreatePage( string cssClass ) {

       return PartialView( "APage", cssClass );
    }

而且我想在APage視圖中使用該CSS類。

例如:

  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>

謝謝

我不確定我是否正確理解了您,但是我認為您的榜樣已經走上正確的道路。

在您的局部視圖中,將此添加到最頂部:

@model string

然后在局部視圖中,將表標記定義更改為

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

繼續@rikitikitik所說的。

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

當然,這假設您使用的是視圖模型 (因此使用MVVM模式 ),而不是“僅”模型甚至數據庫模型(例如由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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM