سؤال

أحاول إضافة التحقق من الصحة إلى طلبي. لدي بعض القواعد التي أحتاج إلى التحقق منها قبل السماح لكتابة المعلومات إلى قاعدة البيانات. لديّ التحقق من صحة البيانات الأساسية إلى النموذج ، لكنني بحاجة أيضًا إلى التأكد من أنه إذا كان لدى أحد الحقول قيمة معينة ، فهذا الحقل الآخر مطلوب. في وقت واحد البرنامج التعليمي 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>

طلب. 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>
<% } %>

MurderdayRow.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>
هل كانت مفيدة؟

المحلول

الأمر بسيط للغاية - تحتاج فقط إلى تطبيق سمة التحقق من الصحة على النموذج بأكمله (أو فئة الطفل). ثم تحصل سمة التحقق من الصحة على إشارة إلى النموذج بدلاً من خاصية واحدة فقط ويمكنك إجراء عمليات الفحص الخاصة بك على خصائص متعددة.

نصائح أخرى

يجب أن تنظر إلى التحقق من صحة كلمة المرور للحصول على مثال على كيفية القيام بذلك.

تحقق من صحة PropertiSMustMatch هنا:

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top