简体   繁体   English

ASP.NET MVC,删除复杂属性类型类型上的[必需]

[英]ASP.NET MVC, Remove [Required] on complex properties types types

I would like to make the sub properties of a complex type required ONLY in certain circunstancies. 我想只在某些情况下才需要复杂类型的子属性。 for this purpose i'm using FoolProof lib. 为此,我正在使用FoolProof库。

For instance, To register a work week schedule. 例如,注册工作周时间表。 I do have a POCO complex class for storing timespans like this: 我确实有一个POCO复杂类,用于存储时间跨度,如下所示:

[ComplexType]
class workDay{

    [Required]
    public TimeSpan start { get; set; }

    [Required]
    public TimeSpan end { get; set; }

    [Required]
    public TimeSpan interval { get; set; }

}

the relevant part of the week POCO class is: 每周POCO课程的相关部分是:

[ComplexType]
class Week{

    [Required]
    public bool monday { get; set; }
    [RequiredIfTrue("monday")]
    public workDay monday_timespan  {get;set;}

    [Required]
    public bool tuesday { get; set; }
    [RequiredIfTrue("tuesday")]
    public workDay tuesday_timespan {get;set;}

    // ...

    [Required]
    public bool sundat { get; set; }
    [RequiredIfTrue("sunday")]
    public workDay sunday_timespan {get;set;}
}

As you can see, the WorkDay class is only required to be filled in if the correspondent day is true. 如您所见,仅在对应的日期为true时才需要填写WorkDay类。

However the validation always require all timespans to be filled. 但是,验证始终需要填写所有时间跨度。 Is somehow possible to disable a required parameter inside a sub complextype parameter based on the Week POCO class? 是否可以基于Week POCO类禁用子复杂类型参数内的必需参数?

You cannot apply validation attributes to complex properties and get client side validation because you do not (and cannot) create a form control for a complex object (only properties of the object). 您不能将验证属性应用于复杂属性并获得客户端验证,因为您不会(也不能)为复杂对象(仅对象的属性)创建表单控件。 You need to create a view model to represent what you want to display in the view (note the nullable properties) 您需要创建一个视图模型来表示要在视图中显示的内容(请注意可为空的属性)

public class DayScheduleVM
{
    public bool IsRequired { get; set; } // this will be used for conditional validation
    [RequiredIf("IsRequired", ErrorMessage = "Please enter the start time")]
    public TimeSpan? StartTime { get; set; }
    [RequiredIf("IsRequired", ErrorMessage = "Please enter the end time")]
    public TimeSpan? EndTime { get; set; }
    [RequiredIf("IsRequired", ErrorMessage = "Please enter the interval")]
    public TimeSpan? Interval { get; set; }
}
public WeekScheduleVM
{
    public DayScheduleVM Sunday { get; set; }
    public DayScheduleVM Monday { get; set; }
    ....
}

and in the view 并认为

@model WeekScheduleVM
....
@using (Html.BeginForm())
{
    <table>
        ....
        <tbody>
            <tr>
                <td>@Html.DisplayNameFor(m => m.Sunday)</td>
                <td>@Html.CheckBoxFor(m => Sunday.IsRequired)</td>
                <td>
                    @Html.TextBoxFor(m => Sunday.StartTime)
                    @Html.ValidationMessageFor(m => Sunday.StartTime)
                </td>
                .... // ditto for EndTime and Interval
            </tr>
            <tr>
                .... // ditto for Monday,Tuesday etc
            </tr>

Then if the check box is checked, you will get a client (and server side) error it the associated StartTime , EndTime and Interval properties are not filled in (its not clear what Interval is for - the name suggests its a calculated value based on StartTime and EndTime so it may not be required in the view) 然后,如果选中此复选框,则将在未填充关联的StartTimeEndTimeInterval属性的情况下收到客户端(和服务器端)错误(它不清楚Interval含义-名称建议其基于以下内容的计算值) StartTimeEndTime因此视图中可能不需要)

You can simplify this further and significantly reduce the amount of code in the view by adding a DayOfWeek enum property to DayScheduleVM 您可以通过将DayOfWeek枚举属性添加到DayScheduleVM来进一步简化此操作,并显着减少视图中的代码量

public DayOfWeek Day { get; set; }

so that in your GET method, you can use 这样您就可以在GET方法中使用

List<DayScheduleVM> model = new List<DayScheduleVM>();
foreach (var day in Enum.GetValues(typeof(DayOfWeek)))
{
    days.Add(new DayScheduleVM { Day = (DayOfWeek)day });
}
return View(model);

and in the view 并认为

@model List<DayScheduleVM>
....
@using (Html.BeginForm())
{
    <table>
        ....
        <tbody>
            @for(int i = 0; i < Model.Count; i++)
            {
                <tr>
                    <td>@Html.DisplayFor(m => m[i].Day)</td>
                    <td>@Html.CheckBoxFor(m => m[i].IsRequired)</td>
                    <td>
                        @Html.TextboxFor(m => m[i].StartTime)
                        @Html.ValidationMessageFor(m => m[i].StartTime)
                    </td>
                    .... // ditto for `EndTime` and `Interval`
                </tr>
            }
        </tbody>
    </table>
    <input type="submit" ... />
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM