1

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

1
  • it may also be worth looking into DataAnnotation, MetaData and a little jQuery.validate so that you dont have to code your way through checking, as it stands you have to do the above code for edit and create and therefor duplicate code. have a search about DataAnnotation is a brilliant tool to get all this done. then add a ModelState.IsValid rather than if this, if that etc etc also there is a new shorthand helper for post now rather than accept verbs you can just use [HttpPost] but for above i will step through and take a look at fac and this will give you are run down of fields and values Commented Mar 7, 2010 at 11:08

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Most likely serie is null.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.