我有一个ASP.NET MVC 4应用程序似乎工作正常.我编写了一个自定义的ValidatorAttribute来确保一个属性的值不小于另一个属性的值.由于涉及两个属性,我重写了IsValid(对象,上下文).
我使用Validator.TryValidateObject和属性的Validate(对象,上下文)成员编写单元测试,并按预期传递.我包含了对有效值和无效值的预期用途的测试.我包含测试,其中属性应用于正确类型的属性,并获得预期的行为(如果任一属性类型错误,我的设计选择是传递.)
我将该属性添加到我的模型中,将其挂钩到应用程序中.就像是:
public abstract class DataElement
{
...
[Required]
public string Version { get; set; }
[StringLength(8, ErrorMessage = "8 characters or less")]
[Required(ErrorMessage = "Required")]
[DisplayName("ID")]
public string DataElementNumber { get; set; }
...
}
public abstract class SimpleElement : DataElement
{
[Required]
[DisplayName("Minimum")]
public int MinimumLength { get; set; }
[Required]
[DisplayName("Maximum")]
[NotSmallerThan("MinimumLength")]
public int MaximumLength { get; set; }
}
public class CodeList: SimpleElement
{
public Collection<CodeValue> Values { get; set; }
}
我有一个类似的控制器
[HttpGet]
public ActionResult Edit(string elementId, string version)
{
CodeList model = Store.GetCodeList(elementId, version);
return View(model);
}
[HttpPost]
public ActionResult Edit(CodeList model)
{
ActionResult result;
if (ModelState.IsValid)
{
Store.Upsert(model);
result = RedirectToAction("Index", "SomeOtherController");
}
else
{
result = View(model.DataElementNumber, model.Version);
}
return result;
}
很简单,我想.如果模型有效,则提交到数据存储.如果它无效,请使用验证消息重新显示表单.如果我在表单中输入有效值,验证程序将按预期运行,即应用程序将值提交到数据存储并继续.
在我输入一个小于Maximum的值的情况下,我正在防范的情况,而不是再次看到我的视图,我看到一个错误屏幕,类似于DataElementNumber =“XML-25的情况“和版本=”201301“
The view ‘XML-25’ or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/CodeListBuilder/XML-25.aspx
~/Views/CodeListBuilder/XML-25.ascx
~/Views/Shared/XML-25.aspx
~/Views/Shared/XML-25.ascx
~/Views/CodeListBuilder/201301.master
~/Views/Shared/201301.master
~/Views/CodeListBuilder/XML-25.cshtml
~/Views/CodeListBuilder/XML-25.vbhtml
~/Views/Shared/XML-25.cshtml
~/Views/Shared/XML-25.vbhtml
~/Views/CodeListBuilder/201301.cshtml
~/Views/CodeListBuilder/201301.vbhtml
~/Views/Shared/201301.cshtml
~/Views/Shared/201301.vbhtml
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException:…
我可以注释掉自定义的NotSmallerThanAttribute并且系统的行为与我期望的一样,除了能够输入小于最小值的最大数量.我不确定如何诊断这个.验证器中的哪种行为会混淆路由引擎?我怎么找到它? TIA
最佳答案 您的问题与验证器无关.
使用result = View(model.DataElementNumber,model.Version);您正在使用View
method:的以下重载
protected internal ViewResult View(
string viewName,
string masterName
)
所以框架认为你的model.DataElementNumber是你的viewName和你的model.Version你的masterName,这就是为什么你得到这个奇怪的视图缺少异常.
要解决此问题,您只需使用correct overload并传入模型即可
result = View(model);
和MVC将负责重新显示以前发布的DataElementNumber和Version值.