Search code examples
htmlasp.netbuttonrazormodel-view-controller

How to enable/disable button based on a value from the ViewModel?


I am setting the following values into the ViewModel in the ActionMethod before passing the ViewModel to the View:

if(toDateNullEntries.Count > 0)
{
    locationsHistoryVM.IsOpen = false;
}
else
{
    locationsHistoryVM.IsOpen = true;
}

In my View, I have the following Button which is disabled from beginning.

<div class="col-md-12 text-center">
    <button type="submit" value="Create" class="btn bgm-orange waves-effect mybtn" id="LocateSubmitButton" disabled>SAVE</button>
</div> 

Now, I want to enable it if the IsOpen value from the ViewModel is true. If not, I want it to remain disabled. How can I do that?

Edit

I tried sending the IsOpen value via ViewBag and then I checked the value with jQuery in the following way:

if(@ViewBag.IsOpen === "false"){
    $('#LocateSubmitButton').removeAttr("disabled");

})

However, I was getting the following error in this case:

Uncaught ReferenceError: False is not defined

On performing Inspect Element, I see that the code is trying to compare False === false.

The reason why I don't want to continue with ViewBag is because I know it is a bad practice and I want to use ViewModel. Is there a way to implement the same using ViewModel?


Solution

  • You can use conditional attributes:

    <button disabled="@(Model.IsOpen == false)">SAVE</button>
    

    If the condition evaluates to true, the attribute will be there, otherwise it will not be there.