0

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 -

1 Answer 1

3
if (string.IsNullOrEmpty(mc.Member.Username) || (mc.Member.Username.Trim()==string.Empty))
{
    ModelState.AddModelError("Member.Username", "Username is required.");
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.