我正在尝试将验证添加到我的应用程序中。在允许将信息写入数据库之前,我需要检查一些规则。我将基本的数据验证添加到模型中,但是我还需要确保如果一个字段具有一定的值,则需要另一个字段。一次是Nerddinner教程 asp.net 介绍了这一点,我过去用它来验证,但是现在我找不到这个或任何其他示例。这是我的模型:

public class DayRequested
{
    public int RequestId { set; get; }
    [Required, DisplayName("Date of Leave")]
    public string DateOfLeave { get; set; }
    [Required, DisplayName("Time of Leave")]
    public string TimeOfLeave { get; set; }
    [Required, DisplayName("Hours Requested")]
    [Range(0.5, 24, ErrorMessage = "Requested Hours must be within 1 day")]
    public double HoursRequested { get; set; }
    [Required, DisplayName("Request Type")]
    public string RequestType { get; set; }
    [DisplayName("Specify Relationship")]
    public string Relationship { get; set; }
    [DisplayName("Nature of Illness")]
    public string NatureOfIllness { get; set; }
    public bool AddedToTimesheet { get; set; }

    public bool IsValid
    {
        get { return (GetRuleViolations().Count() == 0); }
    }

    public IEnumerable<RuleViolation> GetRuleViolations()
    {
        if (String.IsNullOrEmpty(DateOfLeave))
            yield return new RuleViolation("Date of Leave Required", "DateOfLeave");
        if (String.IsNullOrEmpty(TimeOfLeave))
            yield return new RuleViolation("Date of Leave Required", "TimeOfLeave");
        if ((HoursRequested < 0.5) || (HoursRequested > 24))
            yield return new RuleViolation("Hours must be in a period of one day", "HoursRequested");
        if (String.IsNullOrEmpty(RequestType))
            yield return new RuleViolation("Request Type is required", "RequestType");
        if ((!String.IsNullOrEmpty(NatureOfIllness)) && (NatureOfIllness.Length < 3))
            yield return new RuleViolation("Nature of Illness must be longer 2 characters", "NatureOfIllness");

        // Advanced data validation to make sure rules are followed
        LeaveRequestRepository lrr = new LeaveRequestRepository();
        List<LeaveRequestType> lrt = lrr.GetAllLeaveRequestTypes();
        LeaveRequestType workingType = lrt.Find(b => b.Id == Convert.ToInt32(RequestType));

        if ((String.IsNullOrEmpty(Relationship)) && (workingType.HasRelationship))
            yield return new RuleViolation("Relationship is Required", "Relationship");
        if ((String.IsNullOrEmpty(NatureOfIllness)) && (workingType.HasNatureOfIllness))
            yield return new RuleViolation("Nature of Illness is Required", "NatureOfIllness");

        yield break;
    }
}

我的控制器:

    //
    // POST: /LeaveRequest/Create
    [Authorize, HttpPost]
    public ActionResult Create(LeaveRequest leaveRequest, List<DayRequested> requestedDays)
    {
        if (ModelState.IsValid)
        {
            foreach (DayRequested requestedDay in requestedDays)
            {
                requestedDay.RequestId = leaveRequest.RequestId;
                requestedDay.NatureOfIllness = (String.IsNullOrEmpty(requestedDay.NatureOfIllness) ? "" : requestedDay.NatureOfIllness);
                requestedDay.Relationship = (String.IsNullOrEmpty(requestedDay.Relationship) ? "" : requestedDay.Relationship);

                if (requestedDay.IsValid)
                    lrRepository.CreateNewLeaveRequestDate(requestedDay);
                else
                    return View(new LeaveRequestViewModel(leaveRequest, requestedDays, lrRepository.GetLeaveRequestTypes()));
            }

            if (leaveRequest.IsValid)
                lrRepository.CreateNewLeaveRequest(leaveRequest);
            else
                return View(new LeaveRequestViewModel(leaveRequest, requestedDays, lrRepository.GetLeaveRequestTypes()));
        }
        else
            return View(new LeaveRequestViewModel(leaveRequest, requestedDays, lrRepository.GetLeaveRequestTypes()));

        return RedirectToAction("Index", lrRepository.GetLeaveRequests(udh.employeeId));
    }

ModelState.IsValid 尽管代码中的代码 IsValid 运行并确实返回 RuleViolation. 。所以我手动检查 IsValid 它返回 false. 。当我返回视图时,错误消息不会出现。我会想念什么?这是一些视图的片段。

create.aspx

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Create New Leave Request</h2>
    <div><%= Html.ActionLink("Back to List", "Index") %></div>
    <%= Html.Partial("RequestEditor", Model) %>
    <div><%= Html.ActionLink("Back to List", "Index") %></div>
</asp:Content>

请求editor.ascx

<% using (Html.BeginForm()) {%>
    <%= Html.ValidationSummary(true) %>
        <table id="editorRows">
            <% foreach (var item in Model.DaysRequested)
                Html.RenderPartial("RequestedDayRow", new EmployeePayroll.ViewModels.LeaveRequestRow(item, Model.LeaveRequestType)); %>
        </table>
        <p>Type your time to sign your request.</p>
        <p><%= Html.LabelFor(model => model.LeaveRequest.EmployeeSignature) %>: 
            <%= Html.TextBoxFor(model => model.LeaveRequest.EmployeeSignature, new { Class="required" })%>
            <%= Html.ValidationMessageFor(model => model.LeaveRequest.EmployeeSignature)%></p>
        <p><input type="submit" value="Submit Request" /></p>
<% } %>

请求dayrow.ascx

<tbody class="editorRow">
    <tr class="row1"></tr>
    <tr class="row2">
        <td colspan="2" class="relationship">
            <%= Html.LabelFor(model => model.DayRequested.Relationship)%>:
            <%= Html.TextBoxFor(model => model.DayRequested.Relationship) %>
            <%= Html.ValidationMessageFor(model => model.DayRequested.Relationship)%>
        </td>
        <td colspan="2" class="natureOfIllness">
            <%= Html.LabelFor(model => model.DayRequested.NatureOfIllness)%>:
            <%= Html.TextBoxFor(model => model.DayRequested.NatureOfIllness) %>
            <%= Html.ValidationMessageFor(model => model.DayRequested.NatureOfIllness)%>
        </td>
        <td></td>
    </tr>
</tbody>
有帮助吗?

解决方案

这很简单 - 您只需要将验证属性应用于整个模型(或子类)即可。然后,验证属性获取对模型的引用,而不仅仅是一个属性,您可以对多个属性执行检查。

其他提示

您应该查看密码验证,以获取如何执行此操作的示例。

在此处查看propertiesMustMatch验证器:

http://msdn.microsoft.com/en-us/magazine/ee336030.aspx

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top