Asp.net mvc 2 如何将asp.net mvc中的下拉列表设置为只读?
在asp.net MVC模式版本2中,如何在填充后将下拉列表设置为只读?您可以使用jquery禁用下拉列表中的所有选项Asp.net mvc 2 如何将asp.net mvc中的下拉列表设置为只读?,asp.net-mvc-2,Asp.net Mvc 2,在asp.net MVC模式版本2中,如何在填充后将下拉列表设置为只读?您可以使用jquery禁用下拉列表中的所有选项 $("#DropdownID option").attr("disabled","true"); 这将显示选项,但它们是不可选择的。这不起作用,禁用的dropdownlist不会将其选定的值发布到表单帖子上,如果模型属性绑定到dropdownlist,则模型的属性值将作为空值提交。这是一篇旧帖子,但。。。我的首选方法是禁用选项,而不是控件,以便它将所选值发回 public s
$("#DropdownID option").attr("disabled","true");
这将显示选项,但它们是不可选择的。这不起作用,禁用的dropdownlist不会将其选定的值发布到表单帖子上,如果模型属性绑定到dropdownlist,则模型的属性值将作为空值提交。这是一篇旧帖子,但。。。我的首选方法是禁用选项,而不是控件,以便它将所选值发回
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;
}
public static MvcHtmlString SecureDropDownListFor(
这个HtmlHelper HtmlHelper,
表情表情,
IEnumerable selectList,
字符串选项标签,
对象属性,
布勒(总是如此)
{
bool isReadonly=!CurrentUserCanEdit(表达式)| | alwaysReadonly;
var属性=新的RouteValueDictionary(htmlAttributes);
如果(仅限isReadonly)
{
//这将拾取样式,但不会阻止选择其他选项。
添加(“只读”、“只读”);
}
var retval=htmlHelper.DropDownListFor(表达式、选择列表、选项标签、属性);
//禁用列表中除所选选项以外的所有选项;这将允许用户查看其他选项,但不选择一个
如果(仅限isReadonly)
{
retval=new MvcHtmlString(retval.ToHtmlString().Replace(“option value=”,“option disabled=\”disabled\”value=“);
}
返回返回;
}
这样做的效果是,用户可以单击向下箭头查看未选择的选项,但不能选择其中任何一个。由于选择本身未被禁用,因此回发中将仅包括选项和所选值。以下解决方案可以防止用户在dropdownlist上进行任何选择,并且仍然在表单post中提交所选选项的值 标记为只读的下拉列表
@Html.DropDownListFor(model => Model.SomeID, new SelectList(ListOfOptions, "Value", "Text", Model.SomeID), new {@class = "disabled", @readonly = "readonly"})
或者干脆
<select class="disabled" readonly="readonly">...[All your options, one of them selected]...</select>
由下拉列表属性中的@disabled=“disabled”完成,如下所示:
$('select.disabled option:not(:selected)').attr("disabled", "true");