问题描述
我有使用轻微问题的ValidationSummary(真)
显示模型级错误。如果ModelState中不包含模型误差(即 ModelState.AddModelError(,错误描述)
),但包含属性的错误(使用数据注释添加的)它显示验证总之,没有错误信息(当您查看源)。因此,我的CSS是显示像这样一个空的红盒子:
如果没有属性的错误,则显示没有验证摘要。随着的ValidationSummary(真)
我就指望它只能显示验证错误,如果有模型误差。我有什么误解?
我有一个基本的项目如下:
控制器:
公共类HomeController的:控制器
{
公众的ViewResult指数()
{
返回查看();
} [HttpPost]
公众的ActionResult指数(IndexViewModel模型)
{
返回查看();
}
}
型号:
公共类IndexViewModel
{
[需要]
公共字符串名称{;组; }
}
查看:
@model IndexViewModel@ Html.ValidationSummary(真)@using(@ Html.BeginForm())
{
@ Html.TextBoxFor(M = GT; m.Name)
<输入类型=提交值=提交/>
}
我觉得有什么不对的的ValidationSummary
helper方法。你可以很容易地创建一个包装一个自定义的辅助方法内置的ValidationSummary
。
公共静态MvcHtmlString CustomValidationSummary(此的HtmlHelper的HtmlHelper,布尔excludePropertyErrors)
{
VAR htmlString = htmlHelper.ValidationSummary(excludePropertyErrors); 如果(htmlString!= NULL)
{
的XElement XEL = XElement.Parse(htmlString.ToHtmlString()); VAR LIS = xEl.Element(UL)元素(「李先生」)。 如果(lis.Count()== 1安培;&安培; lis.First()值==)。
返回null;
} 返回htmlString;
}
然后从你的观点,
@ Html.CustomValidationSummary(真)
I am having a slight issue with the use of ValidationSummary(true)
to display model level errors. If the ModelState does not contain model errors (i.e. ModelState.AddModelError("", "Error Description")
) but contains property errors (added using data annotations) it displays the validation summary with no error information (when you view the source). My css is therefore displaying an empty red box like so:
If there are no property errors then no validation summary is displayed. With ValidationSummary(true)
I would expect it to only display validation errors if there are model errors. What have I misunderstood?
I have a basic project as follows:
Controller:
public class HomeController : Controller
{
public ViewResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
return View();
}
}
Model:
public class IndexViewModel
{
[Required]
public string Name { get; set; }
}
View:
@model IndexViewModel
@Html.ValidationSummary(true)
@using(@Html.BeginForm())
{
@Html.TextBoxFor(m => m.Name)
<input type="submit" value="submit" />
}
I think there is something wrong with the ValidationSummary
helper method. You could easily create a custom helper method that wraps the built-in ValidationSummary
.
public static MvcHtmlString CustomValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors)
{
var htmlString = htmlHelper.ValidationSummary(excludePropertyErrors);
if (htmlString != null)
{
XElement xEl = XElement.Parse(htmlString.ToHtmlString());
var lis = xEl.Element("ul").Elements("li");
if (lis.Count() == 1 && lis.First().Value == "")
return null;
}
return htmlString;
}
Then from your view,
@Html.CustomValidationSummary(true)
这篇关于为什么的ValidationSummary(真)显示为属性的错误空总结?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!