为什么我的MVC代码没有抛出验证错误?

时间:2017-11-02 12:55:17

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

为什么我的代码不会抛出错误?它将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");        
}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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);