如何在asp.net mvc中下载为readonly?

时间:2010-09-27 09:58:13

标签: asp.net-mvc-2

我怎样才能在asp.net MVC模式版本2中将其下拉为只读?

4 个答案:

答案 0 :(得分:0)

您可以使用jquery禁用下拉列表中的所有选项。

$("#DropdownID option").attr("disabled","true");

这将显示选项,但它们不可选..

答案 1 :(得分:0)

这不起作用,禁用的下拉列表不会在表单帖子上发布它的选定值,如果模型属性绑定到下拉列表,则模型的属性值将作为空值提交。

答案 2 :(得分:0)

这是一个旧帖子,但是......我首选的方法是禁用选项,而不是控件,以便将选定的值发回。

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;
}

这样做的效果是用户可以单击向下箭头并查看未选择的选项,但不能选择其中任何一个。由于选择本身未被禁用,只有选项,所选值将包含在回发中。

答案 3 :(得分:0)

以下是一种解决方案,可以阻止用户在下拉列表中进行任何选择,并仍然在表单帖子中提交所选选项的值。

标记为只读的下拉列表。

@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> 

然后是一个jquery,它将禁用未选中的选项 (这是关键)。

$('select.disabled option:not(:selected)').attr("disabled", "true");