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?
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.
You can achieve this by mixing some c# with Razor code like this:
<button class="btn"
title="Button that can be disabled conditionally by view model property on Razor template\HTML"
type="button"
@{
if (ViewModel.BooleanProperty == true)
{
@:disabled="disabled"
}
}>
Depending on the BooleanProperty value, the disabled attribute will get added to the button's HTML code; otherwise disabled won't be present at all and the button will remain enabled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With