Reputation: 65
I am trying to render a dropdown list as diabled once the on change event has been triggered. I am passing the disabled flag in a viewbag from the controller on httppost. However, the viewbag's name is displaying in teh html flag rather than just the value. Please see my code below:
@Html.DropDownList("dropdown", ViewData["dropdown"] as IEnumerable<SelectListItem>, "--Select--", new { @class = "form-control", id = "dropbox", onchange = "this.form.submit();", ViewBag.propertydisable})
in my controller
ViewBag.propertydisable = "disabled";
How it renders the html:
<select class="form-control" id="dropbox" name="searchparams" propertydisable="disabled" onchange="this.form.submit();" >
<option value="">--Select Budget holder--</option>
<option selected="selected" value="option1">option1</option>
<option value="opt">option2</option>
</select>
How i am wanting it to render is
<select class="form-control" id="dropbox" name="searchparams" disabled onchange="this.form.submit();">
<option value="">--Select Budget holder--</option>
<option selected="selected" value="option1">option1</option>
<option value="opt">option2</option>
</select>
So that the end result once the postback is complete will be disable.
Upvotes: 0
Views: 2775
Reputation:
You need to build an object defining the html attributes based on the ViewBag
property
@{ var attributes = ViewBag.propertydisable ? (object)new { @class = "form-control", disabled = "disabled"} : (object)new { @class = "form-control"}; }
@Html.DropDownList("dropdown", ViewData["dropdown"] as IEnumerable<SelectListItem>, "--Select--", attributes)
Note that you should be setting the ViewBag
property as
ViewBag.propertydisable = true;
Side note: Use Unobtrusive Javascript rather than polluting your markup with behavior. Not sure why you changing the id
attribute from the default "dropdown"
to "dropbox"
but the following assumes you delete the id="dropbox"
attribute
$('#dropdown').change(function() {
$('#form').submit();
});
Upvotes: 3
Reputation: 2126
first of all instead of inline scripting use unobtrusive js. And also you use wrong overload.
Following code should work :
@Html.DropDownList("dropdown",yourlist,new { @class = "form-control", id = "dropbox",disabled=ViewBag.propertydisable})
Update:
$(document).ready(function () {
$('#dropdown').change(function() {
$('#form').submit();
});
Upvotes: 1
Reputation: 11514
Seems hacky to me, but you can conditionally render the element this way by changing your propertydisable to a bool:
@{
if(Viewbag.propertydisable)
{
Html.DropDownList("dropdown",
ViewData["dropdown"] as IEnumerable<SelectListItem>,
"--Select--",
new { @class = "form-control",
id = "dropbox",
onchange = "this.form.submit();",
disabled = "disabled"});
}
else
{
Html.DropDownList("dropdown",
ViewData["dropdown"] as IEnumerable<SelectListItem>,
"--Select--",
new { @class = "form-control",
id = "dropbox",
onchange = "this.form.submit();"});
}
}
Upvotes: 0