如果模型中的属性中存在属性[Editable(false)]
,请尝试创建禁用的文本框。
public static IHtmlString SmartTextBox(this HtmlHelper helper, string content)
{
string htmlString = String.Format("<input type="text">{0}</input>", content);
return new HtmlString(htmlString);
}
型号:
public class User
{
public int Age { get; set; }
[Editable(false)]
public string Name { get; set; }
}
是否有检查模型的方法,然后将禁用的属性添加到输入元素中,如果它被禁用了?
答案 0 :(得分:1)
这是我写的一个帮手,如果模型属性被标记为必需,它会在标签上添加'*'。 ModelMetaData具有可能能够利用的IsReadonly属性。您应该能够进行正确的替换以对文本框进行更改。
public static class LabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression, IDictionary<String, Object> htmlAttributes,
String requiredMarker = "*")
{
return LabelHelper(html, ModelMetadata.FromLambdaExpression(expression, html.ViewData),
ExpressionHelper.GetExpressionText(expression), null, htmlAttributes, requiredMarker);
}
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression, Object htmlAttributes, String requiredMarker)
{
return LabelFor(html, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), requiredMarker);
}
internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, String htmlFieldName,
String labelText = null, IDictionary<String, Object> htmlAttributes = null, String requiredMarker = null)
{
var resolvedLabelText = labelText ??
metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
var tag = new TagBuilder("label");
tag.Attributes.Add("for",
TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
tag.SetInnerText(resolvedLabelText);
tag.MergeAttributes(htmlAttributes, true);
if (metadata.IsRequired && !String.IsNullOrWhiteSpace(requiredMarker))
{
var requiredSpan = new TagBuilder("span") {InnerHtml = requiredMarker};
requiredSpan.AddCssClass("required");
tag.InnerHtml += requiredSpan;
}
var result = tag.ToString(TagRenderMode.Normal);
return new MvcHtmlString(result);
}
}