With ASP.NET Webforms, I could drag and drop a control on a form and be able to access its properties:
if (number == 0)
AddButton.Enabled = false;
Although I cannot drag and drop a control on a ASP.NET MVC View template, can I change its attributes?
For instance:
- disable a button in some conditions and be able to enable it if conditions change.
- Be able to change the text of a button from “Next->” to “Finish”
- etc.
There are (at least) two Methods to do this:
Method 1: The Simple Way
You would do this by adding logic in your view:
Where
Model.numberis the count of items passed to your view by your controller. If it’s less than or equal to zero,disabledwill betrue.The syntax may not be exact, I haven’t tried this, but this is the path I would go down to do what you want.
This will work for the initial setting of the value; changing it without refreshing the page is a matter of using JavaScript, as other answers have pointed out.
Method 2: The overly complex but more ‘MVC’ way
If you want the logic in the controller rather than the view, you should set up a specific ViewModel object that you can add the logic to:
ViewModel
Controller
View
Again, the syntax and usage may be a little off, I’m prototyping this off the top of my head, and am not in a location where I can test this for you.
If you’re interested in ViewModels, here are some good resources:
I’ve updated it to return
disabled=disabledusing the string if it is actually disabled.