Search code examples
c#cssasp.net-mvcrazordynamic-css

How to assign C# variable to CSS class variable in ASP.NET MVC ActionLink


In the ActionLink code below, how can I assign a C# string variable to @class in the view in ASP.NET MVC 5?

@Html.ActionLink("Manage List", "Index", new { @class = "DynamicClassName" });

I want to replace the static string @class = "DynamicClassName" with something dynamic, similar to @class = @myChangingColorClass

// Error 
// yes, myChangingColorClass is declared C# valid string 
@Html.ActionLink("Manage List", "Index", new { @class =  @myChangingColorClass });

Solution

  • This can be do by two ways one is by setting value in ViewModel class or by setting value in ViewBag, ViewData or TempData.

    Way 1) Preffered way Strongly Typed: Set css class name to viewmodel class attribute:

    Class Student
    {
      public ID BIGINT {get; set;}
      ... //other properties
    
    }
    
    Class StudentViewModel : Student
    {
       public CssClass string {get; set;}
    }
    

    //controller action

    public ActionResult Index(){
      StudentViewModel objModel; 
      //initialize model
    
      objModel.CssClass = "myCssClass"; //set css class name to viewmodel 
      return View(objModel);
    }
    

    //in view use code like below:

    @model namespace.StudentViewModel;
    @Html.ActionLink("Manage List", "Index", new { @class =  Model.CssClass })
    

    Way 2) Set css class name to viewbag / viewdata / tempdate. But this is not prefered.

    //controller action

    public ActionResult Index(){
    
      ViewBag.CssClass = "myCssClass"; //set css class name to ViewBag
      //or
      ViewData["CssClass"] = "myCssClass"; //set css class name to ViewData
      //or
      TempData["CssClass"] = "myCssClass"; //set css class name to TempData
    
      return View();
    }
    

    //in view use code like below:

    @Html.ActionLink("Manage List", "Index", new { @class =  @ViewBag.CssClass })
    //Or
    @Html.ActionLink("Manage List", "Index", new { @class =  @Convert.toString(ViewData["CssClass"]) })
    //Or
    @Html.ActionLink("Manage List", "Index", new { @class =  @Convert.toString(TempData["CssClass"]) })
    

    Please let me know, is this works for you?