35

In my controller this code:

[HttpPost]
        public ActionResult Edit(Company company, FormCollection IsCostCenters)
        {
            if (ModelState.IsValid)
            {
                Company objNewCompany = new Company();
                //oParty.CostCenters.Clear();

                using (PaymentAdviceEntityContainer db1 = new PaymentAdviceEntityContainer())
                {
                    objNewCompany = db1.Companies.Find(company.Id);

                    objNewCompany.CostCenters.Clear();

                    string[] temp = IsCostCenters["CostCenters"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var s in temp)
                    {
                        if (s != "false")
                        {

                            CostCenter oCostCenter = new CostCenter();
                            oCostCenter = db1.CostCenters.Find(Convert.ToInt32(s));
                            objNewCompany.CostCenters.Add(oCostCenter);
                        }
                    }
                    db1.SaveChanges();
                }

                db.Entry(company).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CreatedById = new SelectList(db.Employees, "Id", "FirstName", company.CreatedById);
            return View(company);
        }

And my view code as below

@using PaymentAdviceEntity;
@{

    ViewBag.Title = "Edit";
    List<CostCenter> clist = new List<CostCenter>();
    clist = ((List<CostCenter>)ViewBag.CostCenters).ToList();
}



                       <div style="line-height: 22px; width: 100%;height :3%; float: left; ">
                       @{
    foreach (var item in clist)
    {                      
                             <div  style="line-height: 22px; width: 28%; float: left;">
                                                <span class="checkbox">@Html.CheckBox("CostCenters", item.IsChecked, new { @value = item.Id })</span>
                                               <span>@Html.DisplayFor(modelItem => item.Name)</span>

                              </div> 

    }
}

So please what is reason ModelState.IsValid is return false in page post time ...

Iswanto San
  • 18,263
  • 13
  • 58
  • 79
Sraj Mane
  • 355
  • 1
  • 4
  • 5
  • see [this](http://stackoverflow.com/questions/684445/what-can-cause-viewdata-modelstate-isvalid-to-become-false) – Iswanto San Mar 11 '13 at 07:51
  • The parameter conversion from type 'System.String' to type 'PaymentAdviceEntity.CostCenter' failed because no type converter can convert between these types.===> Above Error occurs how to solve this error please tell me – Sraj Mane Mar 11 '13 at 09:41

3 Answers3

142

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

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

Place a break point at the above line and see what are the errors in your ModelState.

Mamun
  • 66,969
  • 9
  • 47
  • 59
Karthik Chintala
  • 5,465
  • 5
  • 30
  • 60
13

As Brad Wilson states in his answer here:

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

Try using :-

if (!ModelState.IsValid)
{
    var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

    // Breakpoint, Log or examine the list with Exceptions.
}

If it helps catching you the error. Courtesy this and this

Community
  • 1
  • 1
Shubh
  • 6,693
  • 9
  • 48
  • 83
  • 1
    When you copy the words of others, you must be explicit in quoting and attributing that wording. I've edited this answer to do this, but you must do this yourself in the future. – Brad Larson Mar 20 '13 at 16:54
  • 2
    @BradLarson , First of all apologies for missing the courtesy part. I have tried putting courtesy part always ; like i have given at the end. This is my mistake if i have missed the link to Brad Wilson's answer. Apologies! – Shubh Mar 20 '13 at 19:18
4

"ModelState.IsValid" tells you that the model is consumed by the view (i.e. PaymentAdviceEntity) is satisfy all types of validation or not specified in the model properties by DataAnotation.

In this code the view does not bind any model properties. So if you put any DataAnotations or validation in model (i.e. PaymentAdviceEntity). then the validations are not satisfy. say if any properties in model is Name which makes required in model.Then the value of the property remains blank after post.So the model is not valid (i.e. ModelState.IsValid returns false). You need to remove the model level validations.

jishnu saha
  • 175
  • 7