How to check for a null object reference when validating forms in MVC

Posted by quakkels on Stack Overflow See other posts from Stack Overflow or by quakkels
Published on 2010-05-28T17:22:55Z Indexed on 2010/05/28 17:32 UTC
Read the original article Hit count: 248

Hello SO,

I'm experimenting with validating forms in the asp.net MVC framework.

I'm focusing on server side validation for the time being. I've come across an error that I'm not sure how to rectify.

System.NullReferenceException: Object reference not set to an instance of an object.

The code that throws the error is:

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create([Bind(Exclude="ID")] MembersCreate mc )
    {
        mc.Modules = ModuleListDataContext.GetModuleList();
        ViewData.Model = mc;

        //Validation using ModelState

        //
        //
        //line below errors when form field is empty
        //
        if ((string)mc.Member.Username.Trim() == "")
            ModelState.AddModelError("Member.Username", "Username is required.");

        if (!ModelState.IsValid)
            return View();

        try
        {
            // TODO: Add insert logic here

            return RedirectToAction("Index","Home");
        }
        catch
        {
            return View();
        }
    }

When I put spaces in the field it performs exactly as i want, but if I leave the field blank and press submit I get the error.

What's the best way to avoid this error and still validate blank form fields?

Thanks all -

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about form-validation