views:

21

answers:

1

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 -

+3  A: 
if (string.IsNullOrEmpty(mc.Member.Username) || (mc.Member.Username.Trim()==string.Empty))
{
    ModelState.AddModelError("Member.Username", "Username is required.");
}
Gregoire
Thanks a ton! That works, but I don't understand how this works and the other code I tried doesn't. It seems to be using the same references as before.
quakkels
If there is no data in the field username, the associated property will be null so you can not call trim on it, so the first thing it does is checking if the username property is null and if not checking if it contains only spaces
Gregoire
Thanks a lot for the explanation.
quakkels