【发布时间】:2023-03-14 02:10:01
【问题描述】:
我的问题: 我只是自定义必需属性,为什么不显示 ProductDescription 的错误消息?
我的所有文件,请参阅以下部分:
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
{
}
}
感谢您的提前!
【问题讨论】:
-
您在
global.asax.cs中注册了您的CustomRequiredAttribute吗?但是该属性的意义何在?它有什么作用? -
哦不@StephenMuecke,我错了,谢谢。我想要自定义必需属性以使错误消息显示为图像,例如
public class ImageRequiredAttribute : RequiredAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { return new ValidationResult("<img src='" + VirtualPathUtility.ToAbsolute("~/Content/images/error.gif") + "' />"); } }
标签: c# validation asp.net-mvc-4 asp.net-mvc-partialview error-messaging