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 -