对于ASP.NET MVC2应用程序自定义的验证规则 [英] Custom validation rules for ASP.NET MVC2 Application
问题描述
我试图验证添加到我的应用程序。我有一些规则,我需要使信息被写入到数据库中之前要检查。我有基本的数据验证添加到模型中,但我也需要确保,如果一个领域具有一定的价值,需要此另一场。曾经有一段时间在 asp.net中的NerdDinner教程覆盖了,我用在过去进行验证,但现在我找不到或任何其他实施例。这里是我的模型:
公共类DayRequested
{
公众诠释的requestId {设置;得到; }
[必填,显示名称(离开日期)]
公共字符串DateOfLeave {搞定;组; }
[必填,显示名称(休假时间)
公共字符串TimeOfLeave {搞定;组; }
[必填,显示名称(时间要求)]
[范围(0.5,24,的ErrorMessage =请求的时间必须在1天内)]
公共双HoursRequested {搞定;组; }
[必填,显示名称(请求类型)]
公共字符串的RequestType {搞定;组; }
[DisplayName的(指定关系)]
公共字符串关系{搞定;组; }
[显示名称(疾病的性质)]
公共字符串NatureOfIllness {搞定;组; }
公共BOOL AddedToTimesheet {搞定;组; } 公共BOOL的IsValid
{
{返回(GetRuleViolations()计数()== 0); }
} 公共IEnumerable的< RuleViolation> GetRuleViolations()
{
如果(String.IsNullOrEmpty(DateOfLeave))
产量返回新RuleViolation(假期所需的日期,DateOfLeave);
如果(String.IsNullOrEmpty(TimeOfLeave))
产量返回新RuleViolation(TimeOfLeave,请假要求日期);
如果((HoursRequested小于0.5)||(HoursRequested> 24))
产量返回新RuleViolation(时间必须是在一个时期一天,HoursRequested);
如果(String.IsNullOrEmpty(请求类型))
产量返回新RuleViolation(请求类型是必需的,请求类型);
如果((String.IsNullOrEmpty(NatureOfIllness))及!及(NatureOfIllness.Length 3;))
产量返回新RuleViolation(疾病的性质必须是长2个字符,NatureOfIllness); //先进的数据验证,以确保规则得到遵守
LeaveRequestRepository LRR =新LeaveRequestRepository();
清单< LeaveRequestType> LRT = lrr.GetAllLeaveRequestTypes();
LeaveRequestType workingType = lrt.Find(B = GT; b.Id == Convert.ToInt32(请求类型)); 如果((String.IsNullOrEmpty(关系))及及(workingType.HasRelationship))
产量返回新RuleViolation(关系是必需的,关系);
如果((String.IsNullOrEmpty(NatureOfIllness))及及(workingType.HasNatureOfIllness))
产量返回新RuleViolation(疾病的自然是必需的,NatureOfIllness); 产生中断;
}
}
我的控制器:
//
// POST:/ LeaveRequest /创建
[授权,HttpPost]
公众的ActionResult创建(LeaveRequest leaveRequest,列表与LT; DayRequested> requestedDays)
{
如果(ModelState.IsValid)
{
的foreach(DayRequested requestedDay在requestedDays)
{
requestedDay.RequestId = leaveRequest.RequestId;
requestedDay.NatureOfIllness =(String.IsNullOrEmpty(requestedDay.NatureOfIllness):requestedDay.NatureOfIllness?);
requestedDay.Relationship =(String.IsNullOrEmpty(requestedDay.Relationship):requestedDay.Relationship?); 如果(requestedDay.IsValid)
lrRepository.CreateNewLeaveRequestDate(requestedDay);
其他
返回查看(新LeaveRequestViewModel(leaveRequest,requestedDays,lrRepository.GetLeaveRequestTypes()));
} 如果(leaveRequest.IsValid)
lrRepository.CreateNewLeaveRequest(leaveRequest);
其他
返回查看(新LeaveRequestViewModel(leaveRequest,requestedDays,lrRepository.GetLeaveRequestTypes()));
}
其他
返回查看(新LeaveRequestViewModel(leaveRequest,requestedDays,lrRepository.GetLeaveRequestTypes())); 返回RedirectToAction(指数,lrRepository.GetLeaveRequests(udh.employeeId));
}
ModelState.IsValid
虽然在code 的IsValid
运行,并不会返回未设置为false一个 RuleViolation
。所以我手动检查的IsValid
返回假
。当我回看,错误信息不会出现。什么可能我会丢失?这里的一些看法片段。
Create.aspx
< ASP:内容ID =内容2ContentPlaceHolderID =日程地址搜索Maincontent=服务器>
< H2>新建请假申请< / H>
< DIV><%= Html.ActionLink(返回目录,索引)%GT;< / DIV>
<%= Html.Partial(RequestEditor模型)%GT;
< DIV><%= Html.ActionLink(返回目录,索引)%GT;< / DIV>
< / ASP:内容>
RequestEditor.ascx
<使用%(Html.BeginForm()){%GT;
<%= Html.ValidationSummary(真)%GT;
<表ID =editorRows>
<%的foreach(在Model.DaysRequested VAR项)
Html.RenderPartial(RequestedDayRow,新EmployeePayroll.ViewModels.LeaveRequestRow(项目,Model.LeaveRequestType)); %GT;
< /表>
< P>输入你的时间来签署您的要求与LT; / P>
&所述p为H.;&下;%= Html.LabelFor(型号= GT; model.LeaveRequest.EmployeeSignature)%计算值:
<%= Html.TextBoxFor(型号=> model.LeaveRequest.EmployeeSignature,新{类=所需的})%GT;
<%= Html.ValidationMessageFor(型号=> model.LeaveRequest.EmployeeSignature)%GT;< / P>
< P><输入类型=提交值=提交申请/>< / P>
<%}%GT;
RequestedDayRow.ascx
< TBODY类=editorRow>
&所述; TR类=ROW1>&下; / TR>
< TR类=ROW2>
< TD合并单元格=2级=关系>
<%= Html.LabelFor(型号=> model.DayRequested.Relationship)%计算值:
<%= Html.TextBoxFor(型号=> model.DayRequested.Relationship)%GT;
<%= Html.ValidationMessageFor(型号=> model.DayRequested.Relationship)%GT;
< / TD>
< TD合并单元格=2级=natureOfIllness>
<%= Html.LabelFor(型号=> model.DayRequested.NatureOfIllness)%计算值:
<%= Html.TextBoxFor(型号=> model.DayRequested.NatureOfIllness)%GT;
<%= Html.ValidationMessageFor(型号=> model.DayRequested.NatureOfIllness)%GT;
< / TD>
< TD>< / TD>
< / TR>
< / TBODY>
这很简单 - 你只需要您的验证属性适用于整个模型(或子类)。然后验证属性获取到模型而不是一个属性的引用,你可以在多个属性执行的检查。
I am attempting to add validation to my application. I have some rules I need to check before allowing the information to be written to the database. I have the basic data validation added to the model, but I also need to make sure that if one field has a certain value, this other field is required. At one time the NerdDinner tutorial at asp.net covered that and I used that in the past for validation, but now I can't find that or any other example. Here is my model:
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;
}
}
My controller:
//
// 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
is not set to false though the code in IsValid
is run and does return a RuleViolation
. So I manually check IsValid
it returns false
. When I return to the view, the error messages do not appear. What might I be missing? Here are some snippets of the views.
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>
RequestEditor.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>
<% } %>
RequestedDayRow.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>
It's quite simple - you just need to apply your validation attribute to the entire model (or a child class). Then the validation attribute gets a reference to the model instead of just one property and you can perform your checks on multiple properties.
这篇关于对于ASP.NET MVC2应用程序自定义的验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!