【问题标题】:Why doesn't my MVC code throw validation error?为什么我的 MVC 代码不会引发验证错误?
【发布时间】:2018-04-15 00:18:18
【问题描述】:

为什么我的代码没有抛出错误?它将 ModelState.IsValid 呈现为 false,这没关系,但当我将 Story 文本框留空时不会引发错误。

它浪费了我一整天,但仍然无法弄清楚发生了什么?

帮帮我。

我不认为它包含任何错误,但它仍然不会抛出我在模型中定义的所需错误。

查看:

<div class="form-group">
    @Html.LabelFor(model => model.Story, htmlAttributes: new { @class = "control-label col-md-2" })

    <div class="col-md-10">
        @Html.EditorFor(model => model.Story, new { htmlAttributes = new { @class = "form-control white" } })
        @Html.ValidationMessageFor(model => model.Story, "", new { @class = "text-danger" })
    </div>
</div>

型号:

namespace HimHer.Models
{
    public class Stories
    {
        public int ID { get; set; }     
        public string Image { get; set; }

        [Required(AllowEmptyStrings=false, ErrorMessage="Story required")]
        public string Story { get; set; }

        public int HiddenID { get; set; }
    }
}

控制器:

[HttpPost]      
public ActionResult AddStories(Stories st, HttpPostedFileBase files)
{
    try
    {
        if (ModelState.IsValid) 
        {
            if (files != null)
            {
                string filePath = Path.Combine(Server.MapPath("~/UploadedFiles/"), Path.GetFileName(files.FileName));
                files.SaveAs(filePath);
            }

            st.Image = Path.GetFileName(files.FileName);
            listofStories.Clear();
            listofStories = bo.GetAllImages();

            if (bo.insertImages(st))
            {
                ViewBag.Data = "Added";
                ViewBag.Grid = listofStories;
                ViewBag.Style = "display:none";
                ViewBag.StyleAdd = "";
            }
            else
            {

            }
        }     
    }
    catch (Exception ex)
    {
        ViewBag.Data = ex.Message;
    }

    return RedirectToAction("AddStories", "Stories");        
}

【问题讨论】:

  • “代码抛出错误”是什么意思?如果您说 Model.IsValid 为假,那么这是预期的行为。在您的操作中,您检查它是否为假 - 在这里没有任何问题。
  • 我相信你遇到了和这里一样的问题:stackoverflow.com/questions/17923622/…
  • 您的意思是提交表单时没有显示错误吗? - 在这种情况下,您没有正确实施客户端验证

标签: c# asp.net asp.net-mvc asp.net-mvc-4 model-view-controller


【解决方案1】:

您必须返回视图才能显示任何错误消息,请尝试在方法的开头添加以下内容:

if (!ModelState.IsValid)
{
   return View(model);
}

【讨论】:

    【解决方案2】:

    如果您的 ModelState 无效,您必须自己显示错误。为此,MVC 使用 ModelState 集成了内置函数,例如:

     [HttpPost]      
     public ActionResult AddStories(Stories st, HttpPostedFileBase files)
     {
            try
            {
                if (!ModelState.IsValid)
                     return View(st);
                [...] // rest of the codes
            }
     }
    

    在你的视图中,如果你想显示错误摘要,添加:

    @Html.ValidationSummary();
    

    或保留您的Html.ValidationMessageFor();

    否则,您可以创建自己的错误处理程序来获取错误列表:

    var allErrors = ModelState.Values.SelectMany(v => v.Errors);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-07
      • 2017-04-26
      • 2020-03-25
      • 1970-01-01
      • 2018-03-18
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多