1

For the life of me I cant figure out why this simple piece of code is not working. I know there are many questions like this here and I 've tried all of them, but I just cant get it to work!

My controller:

 //validate email
            if (studentlist.StudentLiveId == null || !studentlist.StudentLiveId.Contains("@"))
            {
                ModelState.AddModelError("StudentLiveId", "Please enter a valid email id");
                return View(studentlist);
            }

My View - Relevant bit:

@using (Html.BeginForm())
{

    @Html.ValidationSummary(true)

    <fieldset>
        <p style="font-weight: bold; font-size: large; color: red">
            hELLO
        </p>
        <div class="editor-field">
            @Html.ValidationMessageFor(model => model.StudentLiveId)
        </div>

The error:

If I leave the liveid field null , instead of showing an error and stopping, it just skips over the Live Id validation field and goes to some other dropdown field in the model and throws a Object reference not set to instance of an object error!

I am just printing the validation error in another common place and not next to the relevant field. I expect the view to throw the error and stop loading further and not go to the dropdown and show some random error. What is wrong here?

Vrashabh Irde
  • 14,129
  • 6
  • 51
  • 103

1 Answers1

0

The model gets processed and bound to the view regardless of whether there are any ModelState errors, so your expectation is unfortunately incorrect.

If you're getting a null reference error, it usually means you're trying to rebind a collection of some sort to a DropDownList or some other helper that doesn't have a guard against a null collection.

You have to remember that anything not bound to an input of one sort or another doesn't get retained when you post the form. It seems counter-intuitive at times, but the value bound to a dropdownlist is the "selected" value, not the collection of items used to populate the <select> element. So, if your initial action included logic to build an IEnumerable, List, or SelectList (etc.) for your model, you have to repeat that logic in your post action prior to returning the view.

Tieson T.
  • 20,774
  • 6
  • 77
  • 92