将一个css类从控制器传递到asp.net mvc3中的局部视图

时间:2012-07-06 06:41:23

标签: c# asp.net asp.net-mvc-3

我有一个来自控制器的简单代码

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>

  4. 谢谢

2 个答案:

答案 0 :(得分:0)

我不确定我是否理解你,但我认为你的榜样已经走上正轨。

在局部视图中,将其添加到最顶层:

@model string

然后在局部视图中,将表格标签定义更改为

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

答案 1 :(得分:0)

延伸@rikitikitik所说的话。

您已经发现了PartialView(viewName, model)方法重载,现在您只需要扩展当前的model以包含CSS类字符串。只需添加一个名为CssClass的属性,您就可以在局部视图中使用它。

这当然假设您正在使用view models(因而是MVVM pattern),而不是“仅仅”模型甚至数据库模型(例如由实体框架处理)。

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>