简体   繁体   English

Html.ValidationSummary未填充自定义错误ASP.NET MVC剃刀页

[英]Html.ValidationSummary Not Populating with Custom Errors ASP.NET MVC Razor Page

I'm fairly new to MVC, I need to create a custom error that would fire if the user does not select a category. 我是MVC的新手,我需要创建一个自定义错误,如果用户未选择类别,该错误将触发。 However the Html.ValidationSummary is not populating when a product without categories is created. 但是,当创建没有类别的产品时,不会填充Html.ValidationSummary。 Instead the view is returned and shown on the browser without the validation summary being populated. 而是返回视图并将其显示在浏览器上,而无需填充验证摘要。 Please see below, I've have copied the relevant code over. 请参阅下面,我已经复制了相关代码。
CSHTML CODE CSHTML代码

@Html.ValidationSummary(false, "", new { @class = "text-danger" })

CONTROLLER CODE 控制器代码

if (!model.HasCategories)
{
     ModelState.AddModelError(string.Empty, "A category is required.");
}

if(!ModelState.IsValid()) {
    return RedirectToAction("addEditProduct", new { id = model.P.ID});
}

when you are using ModelState errors you should use return View() instead of Redirect 当您使用ModelState错误时,应使用return View()而不是Redirect

    public ActionResult addEditProduct()
    {
        return View();
    }

    [HttpPost]
    public ActionResult addEditProduct(EditProductModel model)
    {
        if (!model.HasCategories)
        {
            ModelState.AddModelError(string.Empty, "A category is required.");
            return View(new { id = model.P.ID });
        }

        if (!ModelState.IsValid())
        {
            return View(new { id = model.P.ID });
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM