tan*_*ava 0 javascript asp.net-mvc html.dropdownlistfor
我试图在我的mvc应用程序中基于model属性禁用或启用dropdownlistfor: -
我在做的是: -
@Html.DropDownListFor(m => m.ParentOrganisationID, new SelectList(Model.ParentOrganisations, "ID", "Name", Model.ParentOrganisationID), new { @id = "ddlParentOrganisations", @class = "form-control css-select", @disabled = Model.IsReadOnly ? "disabled" : "false", @style = "width:40%; height:10%;" })
Run Code Online (Sandbox Code Playgroud)
但即使模型属性"model.IsReadOnly"为false,它也会将下拉列表显示为已禁用.
请建议如何处理此问题,而不使用任何JavaScript
提前致谢
在调用DropDownListForhelper方法中不可能包含条件(if/ternary语句),因为你不能传递一行c#代码(带有你的if条件),它需要一个html属性的对象.此外,以下所有标记都将呈现禁用的SELECT.
<select disabled></select>
<select disabled="disabled"></select>
<select disabled="false"></select>
<select disabled="no"></select>
<select disabled="usingJqueryEnablePlugin"></select>
<select disabled="enabled"></select>
Run Code Online (Sandbox Code Playgroud)
您可以使用if条件检查Model属性的值,并有条件地呈现禁用的版本.
@if (!Model.IsReadOnly)
{
@Html.DropDownListFor(s => s.ParentOrganisationID,
new SelectList(Model.ParentOrganisations, "ID", "Name"))
}
else
{
@Html.DropDownListFor(s => s.ParentOrganisationID,
new SelectList(Model.ParentOrganisations, "ID", "Name"),new {disabled="disabled"})
}
Run Code Online (Sandbox Code Playgroud)
您可以考虑创建一个自定义的html辅助方法来处理if条件检查.
public static class DropDownHelper
{
public static MvcHtmlString MyDropDownListFor<TModel, TProperty>
(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectItems,
object htmlAttributes,
bool isDisabled = false)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression,
htmlHelper.ViewData);
IEnumerable<SelectListItem> items =
selectItems.Select(value => new SelectListItem
{
Text = value.Text,
Value = value.Value,
Selected = value.Equals(metadata.Model)
});
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (isDisabled && !attributes.ContainsKey("disabled"))
{
attributes.Add("disabled", "disabled");
}
return htmlHelper.DropDownListFor(expression,items, attributes);
}
}
Run Code Online (Sandbox Code Playgroud)
现在在你的剃刀视图中,调用这个帮助器
@Html.MyDropDownListFor(s=>s.ParentOrganisationID,
new SelectList(Model.ParentOrganisations, "ID", "Name")
,new { @class="myClass"},Model.IsReadOnly)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2774 次 |
| 最近记录: |