當我點擊提交索引頁按鈕,看到下面的圖片: MVC 4部分視圖上的自定義驗證不顯示錯誤消息?
我的問題: 我只是習慣所要求的屬性,爲什麼產品描述錯誤信息不顯示?
我所有的文件,請參閱以下部分:
ProductModel.cs
namespace TestCustomValidation.Models
{
public class ProductModel
{
[Required(ErrorMessage = "It's for test for ProductName")]
public string ProductName { get; set; }
[CustomRequired(ErrorMessage = "It's for test for ProductDescription")]
public string ProductDescription { get; set; }
}
}
index.cshtml
...
@{Html.RenderAction("Form");}
...
_FormPartial.cshtml
個@model TestCustomValidation.Models.ProductModel
@using (Html.BeginForm("FormSubmit", "Home", new { @id = "form", @name = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<table cellpadding="0" cellspacing="0">
<tr>
<th colspan="2" align="center">Person Details</th>
</tr>
<tr>
<td>Name: </td>
<td>
@Html.TextBoxFor(m => m.ProductName)
</td>
<td>
@Html.ValidationMessageFor(m => m.ProductName)
</td>
</tr>
<tr>
<td>Description: </td>
<td>
@Html.TextBoxFor(m => m.ProductDescription)
</td>
<td>
@Html.ValidationMessageFor(m => m.ProductDescription)
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
}
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public PartialViewResult Form()
{
ProductModel model = new ProductModel();
return PartialView("_FormPartial", model);
}
[HttpPost]
public ActionResult FormSubmit(ProductModel model)
{
if (ModelState.IsValid)
{
string name = model.ProductName;
return RedirectToAction("About");
}
return PartialView("_FormPartial", model);
}
}
CustomRequiredAttribute.cs
namespace TestCustomValidation.CustomValidation
{
public class CustomRequiredAttribute : RequiredAttribute
{
}
}
謝謝提前!
有您註冊'CustomRequiredAttribute'在'global.asax.cs'?但是這個屬性的意義是什麼?它有什麼作用? –
Oh no @StephenMuecke,我的錯誤,謝謝。我想自定義需要的屬性,使錯誤信息顯示爲圖像,比如'公共類ImageRequiredAttribute:RequiredAttribute標籤 { 保護覆蓋的ValidationResult的IsValid(對象的值,ValidationContext validationContext) { 返回新的ValidationResult( 「」); } }' – Elliwood