我同意上面jrummell的解决方案:
当您使用EditorFor
- 扩展,你必须写一个自定义的
编辑器模板来描述可视化组件。
在某些情况下,我认为使用编辑器模板有点僵硬
具有相同数据类型的多个模型属性。就我而言,我想在模型中使用十进制货币值,该值应显示为格式化字符串。我想在我的视图中使用相应的 CSS 类来设置这些属性的样式。
我见过其他实现,其中 HTML 参数已使用模型中的注释附加到属性中。我认为这很糟糕,因为视图信息(如 CSS 定义)应该在视图中设置,而不是在数据模型中设置。
因此我正在研究另一个解决方案:
我的模型包含一个decimal?
属性,我想将其用作货币字段。
问题是,我想使用数据类型decimal?
在模型中,但显示
视图中的十进制值作为使用格式掩码的格式化字符串(例如“42,13 €”)。
这是我的模型定义:
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal? Price { get; set; }
格式掩码0:C2
格式化decimal
保留 2 位小数。这ApplyFormatInEditMode
很重要,
如果您想使用此属性来填充视图中的可编辑文本字段。所以我把它设置为true
,因为就我而言,我想将其放入文本字段中。
通常你必须使用EditorFor
- 视图中的扩展如下:
<%: Html.EditorFor(x => x.Price) %>
问题:
我无法在此处附加 CSS 类,因为我可以使用Html.TextBoxFor
例如。
提供自己的 CSS 类(或其他 HTML 属性,例如tabindex
, or readonly
)与EditorFor
-扩展是编写一个自定义的HTML-Helper,
喜欢Html.CurrencyEditorFor
。这是实现:
public static MvcHtmlString CurrencyEditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Object htmlAttributes)
{
TagBuilder tb = new TagBuilder("input");
// We invoke the original EditorFor-Helper
MvcHtmlString baseHtml = EditorExtensions.EditorFor<TModel, TValue>(html, expression);
// Parse the HTML base string, to refurbish the CSS classes
string basestring = baseHtml.ToHtmlString();
HtmlDocument document = new HtmlDocument();
document.LoadHtml(basestring);
HtmlAttributeCollection originalAttributes = document.DocumentNode.FirstChild.Attributes;
foreach(HtmlAttribute attr in originalAttributes) {
if(attr.Name != "class") {
tb.MergeAttribute(attr.Name, attr.Value);
}
}
// Add the HTML attributes and CSS class from the View
IDictionary<string, object> additionalAttributes = (IDictionary<string, object>) HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
foreach(KeyValuePair<string, object> attribute in additionalAttributes) {
if(attribute.Key == "class") {
tb.AddCssClass(attribute.Value.ToString());
} else {
tb.MergeAttribute(attribute.Key, attribute.Value.ToString());
}
}
return MvcHtmlString.Create(HttpUtility.HtmlDecode(tb.ToString(TagRenderMode.SelfClosing)));
}
这个想法是使用原来的EditorFor
- 生成 HTML 代码并解析此 HTML 输出字符串以替换创建的扩展
CSS Html-Attribute 带有我们自己的 CSS 类并附加其他附加 HTML 属性。对于 HTML 解析,我使用 HtmlAgilityPack(使用 google)。
在视图中你可以像这样使用这个助手(不要忘记将相应的命名空间放入web.config
在你的视图目录中!):
<%: Html.CurrencyEditorFor(x => x.Price, new { @class = "mypricestyles", @readonly = "readonly", @tabindex = "-1" }) %>
使用这个助手,您的货币价值应该在视图中很好地显示。
如果您想发布视图(表单),那么通常所有模型属性都会发送到控制器的操作方法。
在我们的例子中,将提交一个字符串格式的十进制值,该值将由 ASP.NET MVC 内部模型绑定类处理。
因为这个模型绑定器期望decimal?
-value,但是获取字符串格式的值,会抛出异常。所以我们必须
将格式化的字符串转换回原来的格式decimal?
- 代表。因此一个自己的ModelBinder
- 实施是必要的,这
将货币小数值转换回默认小数值(“42,13 €”=>“42.13”)。
以下是此类模型绑定器的实现:
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
object o = null;
decimal value;
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var modelState = new ModelState { Value = valueResult };
try {
if(bindingContext.ModelMetadata.DataTypeName == DataType.Currency.ToString()) {
if(decimal.TryParse(valueResult.AttemptedValue, NumberStyles.Currency, null, out value)) {
o = value;
}
} else {
o = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
}
} catch(FormatException e) {
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return o;
}
}
活页夹必须在global.asax
您的申请文件:
protected void Application_Start()
{
...
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
...
}
也许该解决方案会对某人有所帮助。