ca9163d9
ca9163d9

Reputation: 29159

ModelState.IsValid is false

I have an auto scaffold view

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Event</h4>
        <hr />
        @Html.ValidationSummary(true)

And the controller is

   [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(EventCreateViewModel eventVM)
    {
        if (ModelState.IsValid) // Always false
        {
            var @event = new Event
            {
                EventName = eventVM.EventName,
                ......
                CreateTime = DateTime.Now,
                CreatedBy = User.Identity.Name,
            };
            AddOrUpdateCategories(@event, eventVM.Categories);
            db.Events.Add(@event);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        return View(eventVM);
    }

It doesn't save the data. And the ModelState.IsValid is always false. There is no message show in the html page @Html.ValidationSummary(true). How to get the reason of the failure?

Upvotes: 0

Views: 658

Answers (3)

Krahu
Krahu

Reputation: 183

Add breakpoint to the line with "if (ModelState.IsValid)" Look into ModelState... there are 2 arrays - I think "Keys" and "Values". In Values array you can find what is wrong (is set to false) and in Keys you will find source of problem (look at the same index).

Upvotes: 0

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

If you want to see all validation errors in validation summary, you should use it with false flag:

@Html.ValidationSummary(false)

Upvotes: 3

Tieson T.
Tieson T.

Reputation: 21192

@Html.ValidationSummary(true) means that all model property errors are suppressed from the summary. In order to see those errors, you have to add the individual validation messages:

@Html.ValidationMessageFor(m => m.YourModelProperty)

Upvotes: 0

Related Questions