0

Here, I'm simply checking if some codes are valid for the type of report that they are used in, and also if there are same occurances of codes. I paused the code (with F9) on the first line of this function, and checked the ModelState.IsValid, and it said that it is false.

[HttpPost]
    public ActionResult Edit(ReportEditModel report)
    {
        // some preparation code here
        foreach (PairViewModel pair in report.Pairs)
        {
            if (pair.CodeId == 0 && pair.Amount == 0) continue;

            if (!validCodes.Contains(pair.CodeId))
                ModelState.AddModelError("WrongCode", "Kod " + pair.CodeId + " ne postoji");

            foreach(PairViewModel pair2 in report.Pairs)
                if(pair.CodeId == pair2.CodeId && pair != pair2)
                    ModelState.AddModelError("DoubleCode", "Kod " + pair.CodeId + " se ponavlja više od jednog puta");
        }

        if (!ModelState.IsValid)
            return View(report);

        var newPairs = from r in report.Pairs
                       select new Pair()
        // blah, blah, blah...

I'm having trouble understanding why my model is invalid all the time. I have no Annotations in any of my models, so the only way to say: "Hey model, there is an error!" is by using ModelState.AddModelError, but the line if (!ModelState.IsValid) return View(report); always fires. I the ModelState.IsValid is always false, but I can't see any errors in ModelState.

There is only 1 property of model in question, a public IList<int> ValidCodes { get; set; }, that is empty when it comes back from view to this action.

Please, point me the mistake in my code, if any. How can I check for errors other than pausing at some X line of code and howering over MouseState to check it's keys and errors?

Monset
  • 648
  • 5
  • 25
  • 1
    This might help [How to figure out which key of ModelState has error](http://stackoverflow.com/questions/15296069/how-to-figure-out-which-key-of-modelstate-has-error/15296109#15296109) – Shyju Dec 15 '16 at 18:08
  • Was your intention to return View(report) when the model is valid or invalid. Debug through the code and see what the model state has in its error list – Dan Hunex Dec 15 '16 at 19:55
  • `var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0).Select(k => new { propertyName = k, errorMessage = ModelState[k].Errors[0].ErrorMessage });` –  Dec 15 '16 at 22:37

0 Answers0