1

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");        
}
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
  • What do you mean by "code throw error"? If you say that Model.IsValid is false then it is the expected behavior. In your action you check whether it is false or not - there is no matter to throw an error here. – Andrey Stukalin Nov 02 '17 at 13:00
  • I believe you are experiencing the same issue as here: https://stackoverflow.com/questions/17923622/modelstate-isvalid-even-when-it-should-not-be – user1934587390 Nov 02 '17 at 13:01
  • DO you mean your not getting the error displayed when you submit the form? - in which case you have not implemented client side validation correctly –  Nov 02 '17 at 21:15

2 Answers2

2

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);
}
Hussein Salman
  • 7,806
  • 15
  • 60
  • 98
2

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);
GGO
  • 2,678
  • 4
  • 20
  • 42