简体   繁体   中英

Why doesn't my MVC code throw validation error?

Why doesn't my code throw error? It renders ModelState.IsValid as false, that's ok but doesn't throw the error when I leave Story textbox empty.

It has wasted my whole day but still can't figure out that what has happened?

Help me with it.

I don't think that it contains any mistake but still, it doesn't throw the required error that I have defined in the model.

View:

<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>

Model:

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; }
    }
}

Controller:

[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");        
}

You have to return the view in order to show any error messages, try adding this at the beginning of your method:

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

If your ModelState is not valid you have to display the error yourself. To do that, MVC integrates built-in functions using ModelState like :

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

And in your View, if you want to display the error summary, add :

@Html.ValidationSummary();

or keep your Html.ValidationMessageFor();

Otherwise, you can make your own errors handler getting the error list with :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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