Reputation: 117
I am aware there are similar questions. I have read through pretty much all of them (unless someone can prove otherwise).
I'm writing a help desk application as a practice project to improve my programming skills.
I have a Create action that creates a 'Ticket' as part of that I wish to set the 'State' of that 'Ticket' to 'New'. The reason I want it to be disabled is that only users with admin role should be able to update the state (Inprogress, onhold, resolved, closed etc).
Here is what I've tried so far:
<div class="form-group">
@Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@if (User.IsInRole("Admin"))
{
@Html.DropDownListFor(m => m.State, Model.States, htmlAttributes: new { @class = "form-control" })
}
else
{
@Html.DropDownListFor(m => m.State, Model.States, new { @class = "form-control", @disabled = "disabled", @id = "FakeStates" })
@Html.HiddenFor(m => m.State, Model.States)
}
@Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
</div>
</div>
The problem: The value doesn't make it to the controller and the ultimately the db column is null.
I may have overlooked something simple, if so could someone please take a look and point it out?
Thanks.
Upvotes: 1
Views: 932
Reputation: 96
You need to rearrange the ordering of your elements and put the HiddenFor above the DropDownListFor.
This is because when a form is submitted, the first input with the matching id to the model is returned.
It is also worth nothing that disabled inputs are not returned when posting to the controller. So I believe what's happening is your disabled dropdown is being found before the hidden and is therefore submitting a null value.
I've noticed you've tried adding a different id to the DropDownListFor, however I'm not sure how this works in terms of correct model binding.
Another option would be to show a label instead of a disabled dropdown.
Upvotes: 3
Reputation: 23
Try this:
@Html.HiddenFor(m => m.State, new { Value = Model.States })
ps: is there the value in Model.States?
Upvotes: 1