Search code examples
c#jqueryasp.netasp.net-mvcrazor

How to maintain visibility state of controls?


ASP.NET MVC is stateless,

How to maintain visibility state of controls?

e.g. I have a button control
I hide the button control using jquery
Now when I post-back the button appears again

I wonder if there is any workaround for this.


Solution

  • Assuming you are using strongly typed view models this is one approach you could take.

    Create a view model with a bool property to represent that a property is shown i.e.

    View Model

    public class AModel
    {
        public bool IsShown { get; set; }
    }
    

    Render this as a hidden for in your view which will allow state to be passed to and from the server.

    View

    @Html.HiddenFor(m => m.IsShown)
    

    In your javascript make sure you set the value of the hidden field with:

    $('#IsShown').val(true);
    

    or:

    $('#IsShown').val(false);
    

    This will allow the state of the shown control to be posted back.

    Then make sure your javascript hides or displays the control by passing in the IsShown property. Please note the below needs to use your actual button id.

    Javascript

    $(function(){
     $('#AButtonId').toggle(@Model.IsShown.ToString().ToLower());
    });