Reputation:
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
?
Upvotes: 4
Views: 5344
Reputation: 102378
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.
Upvotes: 1
Reputation: 174299
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.
Upvotes: 2
Reputation: 3301
The following makes the output of "disabled" conditional based on a value from the model:
<button type="submit" value="Create" class="btn bgm-orange waves-effect mybtn" id="LocateSubmitButton" @if (!Model.IsOpen) { <text>disabled</text> }>SAVE</button>
if you wanted to do what you tried with the ViewBag, it would look like this:
if("@ViewBag.IsOpen" === "False"){
$('#LocateSubmitButton').removeAttr("disabled");
})
Notice, the quotes around the item so the comparison becomes "False" === "False" at runtime.
Upvotes: 0