how to make dropdown in asp.net mvc as readonly?
How can i make drop down as read only in the asp.net MVC Pattern version 2 afte开发者_Python百科r it filles?
You could use jquery to disable all options in the dropdown.
$("#DropdownID option").attr("disabled","true");
This will show the options, but they are not selectable..
This doesn't work, a disabled dropdownlist does not post it's selected value on a form post, if a model property is bound to the dropdownlist the model's property value will be submitted as a null value.
This is an old post, but... my preferred method is to disable the options, not the control, so that it posts the selected value back.
public static MvcHtmlString SecureDropDownListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
string optionLabel,
object htmlAttributes,
bool alwaysReadonly)
{
bool isReadonly = !CurrentUserCanEdit(expression) || alwaysReadonly;
var attributes = new RouteValueDictionary(htmlAttributes);
if (isReadonly)
{
// This will pick up the style but not prevent a different option from being selected.
attributes.Add("readonly", "readonly");
}
var retval = htmlHelper.DropDownListFor(expression, selectList, optionLabel, attributes);
// Disable all but the selected option in the list; this will allow user to see other options, but not select one
if (isReadonly)
{
retval = new MvcHtmlString(retval.ToHtmlString().Replace("option value=", "option disabled=\"disabled\" value="));
}
return retval;
}
The effect of this is that the user can click the down arrow and see the unselected options, but can't select any of them. Since the select itself is not disabled, only the options, the selected value will be included in the postback.
The following is a solution that can prevent users from making any selection on the dropdownlist and still submit the value of the selected option in a form post.
A dropdownlist marked as readonly.
@Html.DropDownListFor(model => Model.SomeID, new SelectList(ListOfOptions, "Value", "Text", Model.SomeID), new {@class = "disabled", @readonly = "readonly"})
or simply
<select class="disabled" readonly="readonly">...[All your options, one of them selected]...</select>
And then a jquery that will disable the options that are not selected (that is the key).
$('select.disabled option:not(:selected)').attr("disabled", "true");
精彩评论