【问题标题】:Asp.Net MVC5 - Editorfor template, how to set field as not required?Asp.Net MVC5 - 模板编辑器,如何将字段设置为不需要?
【发布时间】:2014-05-12 09:54:35
【问题描述】:

我正在尝试对复杂属性使用编辑器模板,但模板中的字段默认设置为要求用户填写。有没有一种简单的方法可以避免这种情况并仍然使用“editorfor” ?我知道有一个 [required] 数据注释,但我没有使用它,也找不到相反的命令。模板显示正确,我只是不希望这些字段是必需的。

我的视图模型中的属性:

[UIHint("EditPriceInfo")]
[Display(Name="Price info")]
public PriceInfo PriceInfo { get; set; }

来自模板文件“/Views/Shared/EditorTemplates/EditPriceInfo.cshtml”。 (通过“PriceInfo”类的脚手架创建,见下文。):

@model MyProject.Models.PriceInfo

<div class="form-group">
    @Html.LabelFor(model => model.HourPrice, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.HourPrice)
        @Html.ValidationMessageFor(model => model.HourPrice)
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.DayPrice, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.DayPrice)
        @Html.ValidationMessageFor(model => model.DayPrice)
    </div>
</div>

从“编辑”视图调用模板:

<h4>@Html.DisplayNameFor(model => model.PriceInfo)</h4>

<div class="form-group">
    <div class="col-md-10">
        @Html.EditorFor(model => model.PriceInfo)
        @Html.ValidationMessageFor(model => model.PriceInfo)
    </div>
</div>

以及原始“PriceInfo”实体中的属性:

[Display(Name = "Price/hour")]
public decimal HourPrice { get; set; }
[Display(Name = "Price/day")]
public decimal DayPrice { get; set; }

【问题讨论】:

    标签: asp.net-mvc-5


    【解决方案1】:

    根据this related question 接受的答案:

    ModelMetadata.IsRequired 会告诉您RequiredAttribute 是否需要复杂类型(或包裹在Nullable 中的值类型),但对于不可为空的值类型(因为它们是隐式需要的),它会给您误报。

    这意味着我的示例中的属性将是“隐式必需的”,因为它是一个未包装在 Nullable 中的复杂类型。我通过将“PriceInfo”实体类中的属性设置为可为空来解决问题,如下所示(类型后的问号):

    [Display(Name = "Price/hour")]
    public decimal? HourPrice { get; set; }
    [Display(Name = "Price/day")]
    public decimal? DayPrice { get; set; }
    

    【讨论】:

      猜你喜欢
      • 2012-10-17
      • 2014-08-18
      • 2012-01-06
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多