开发者

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

开发者 https://www.devze.com 2023-01-01 15:59 出处:网络
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.

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();
        View开发者_JAVA技巧Data.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 -


if (string.IsNullOrEmpty(mc.Member.Username) || (mc.Member.Username.Trim()==string.Empty))
{
    ModelState.AddModelError("Member.Username", "Username is required.");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号