Jor*_*dan 23 asp.net-mvc html5 asp.net-mvc-5
我有这行代码:
@Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
Run Code Online (Sandbox Code Playgroud)
我的视图数据字典中有一个名为Readonly的变量.如果ViewBag.Readonly为true,我如何将Quantity设为只读,如果为false则不读取?
简单的事情,但Razor与HTML(古老)的结合使得其他简单的事情变得不可能.
编辑:
我不想使用if语句.这是最后的手段,因为它违反了DRY,我过去曾经多次严重烧伤因为没有跟随.
我上面的这一行确实有效,因为它使文本框只读.我需要根据我的视图状态制作这个条件.
解:
我使用了以下内容.它仍然是DRY违规,但它将它减少到一行.
@Html.EditorFor(model => model.Quantity, new { htmlAttributes = ViewBag.Readonly ? (object)new { @class = "form-control", @readonly = "htmlsucks" } : (object)new { @class = "form-control" } })
Run Code Online (Sandbox Code Playgroud)
Anj*_*jyr 28
编辑:MVC 5
调节器
ViewBag.Readonly=true;//false
Run Code Online (Sandbox Code Playgroud)
视图
@Html.EditorFor(model => model.Quantity, ViewBag.Readonly ? (object)new { htmlAttributes = new { @readonly = "readonly", @class = "form-control" }} : new { htmlAttributes = new { @class = "form-control" } })
Run Code Online (Sandbox Code Playgroud)
今天我必须处理这个问题,因为我必须动态地为Html.TextBoxFor元素设置“只读”属性。我最终编写了以下辅助方法,该方法使我能够在保持 DRY 方法的同时解决该问题:
/// <summary>
/// Gets an object containing a htmlAttributes collection for any Razor HTML helper component,
/// supporting a static set (anonymous object) and/or a dynamic set (Dictionary)
/// </summary>
/// <param name="fixedHtmlAttributes">A fixed set of htmlAttributes (anonymous object)</param>
/// <param name="dynamicHtmlAttributes">A dynamic set of htmlAttributes (Dictionary)</param>
/// <returns>A collection of htmlAttributes including a merge of the given set(s)</returns>
public static IDictionary<string, object> GetHtmlAttributes(
object fixedHtmlAttributes = null,
IDictionary<string, object> dynamicHtmlAttributes = null
)
{
var rvd = (fixedHtmlAttributes == null)
? new RouteValueDictionary()
: HtmlHelper.AnonymousObjectToHtmlAttributes(fixedHtmlAttributes);
if (dynamicHtmlAttributes != null)
{
foreach (KeyValuePair<string, object> kvp in dynamicHtmlAttributes)
rvd[kvp.Key] = kvp.Value;
}
return rvd;
}
Run Code Online (Sandbox Code Playgroud)
它可以通过以下方式使用:
var dic = new Dictionary<string,object>();
if (IsReadOnly()) dic.Add("readonly", "readonly");
Html.TextBoxFor(m => m.Name, GetHtmlAttributes(new { @class="someclass" }, dic))
Run Code Online (Sandbox Code Playgroud)
该代码非常不言自明,但我也在我的博客上的这篇文章中解释了底层逻辑。
非常简单 像这样做。
@if((bool)ViewBag.Readonly)
{
@Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
}
else
{
@Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })
}
Run Code Online (Sandbox Code Playgroud)