Search code examples
javascriptjqueryhtmlasp.net-mvcasp.net-mvc-5

Change html elemts style from Controllers ActionResult in ASP.NET MVC 5


I am making an if check in the controller

if(validDate<DateTime.Now)
{
   //TODO
}

And what I want to do is to hide a specific button in my view if this statement is true, otherwise show it. I am also using jquery in front end. Can someone help me to manipulate the html element, the button, from the controller, example add a style class or something? In this case I need to make the changes from the controller and not from the jquery, but I can use the jquery after if needed.


Solution

  • You need to use models (aka as ViewModel), @thomashaid already gave you a comment with a useful article: Views And ViewModels.

    Create a class in the "Models" folder of your MVC Project. Like this:

    public class MyViewModel
    {
        public bool ShowButton { get; set; }
    }
    

    Then in your controller, create an object of your ViewModel class and assign the corresponding value to the ShowButton property. Then pass the ViewModel to the returning view:

    public ActionResult MyAction()
    {
        var myViewmodel = new MyViewModel();´
    
        if(validDate < DateTime.Now)
        {
            myViewModel.ShowButton = true;
        }
    
        return View(myViewModel);
    }
    

    Finally, use razor syntax in your view to manipulate the HTML code that will be returned to the client:

    @model MyViewModel
    
    @if (Model.ShowButton)
    {
        <Button>now you see me</Button>
    }