alinpopescu
alinpopescu

Reputation: 73

Validation textbox in MVC

I have the following code and I don't know were is the mistake:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(factura fac)
    {
        if (fac.numar>0)
            ModelState.AddModelError("numar", "Numar este invalid .");
        if (fac.serie.Trim().Length == 0)
            ModelState.AddModelError("serie", "Serie invalida");

        if (!ModelState.IsValid) return View("Create", fac);

    }

Here I try validate an textbox "serie" and I got the following error

Object reference not set to an instance of an object.

Thank you

Upvotes: 1

Views: 81

Answers (2)

Romias
Romias

Reputation: 14133

Check string.IsNullOrEmpty(fac.serie) or string.IsNullOrWhitespace(fac.serie)

Most likely serie is null.

Upvotes: 0

Bobby
Bobby

Reputation: 1676

First, could you please re-format to make easier to read? ie put all the code in a block?

Next, debug and check these expressions to see if they're null:

  • fac.serie
  • fac

It looks like either being null could throw this exception. It's probably the latter. If appropriate, wrap in a guard condition to check if it is null before evaluating.

Upvotes: 1

Related Questions