0

I have a textbox called pass in my Create view

<div class="form-group">
       @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
       <div class="col-md-10">
            @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
</div>

In my AccountController, I tried to validate the password between 8 to 250 letters, the code doesnt seem to work properly as when I tried to run the website, it return error: 'Cannot perform runtime binding on a null reference'

            if (ModelState.IsValid)
            {
                db.Accounts.Add(account);
                if(ViewBag.Password.Length > 8 && ViewBag.Password != null)
                {
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                else return RedirectToAction("Create");
Tony Wolf
  • 3
  • 6
  • Your Viewbag is Empty or null so you got this error please refer [Link](https://stackoverflow.com/questions/40531522/mvc5-c-sharp-cannot-perform-runtime-binding-on-a-null-reference) if you want more detail of validation please check [Link](https://www.c-sharpcorner.com/UploadFile/3d39b4/Asp-Net-mvc-server-side-validation/) – Niraj Mar 20 '20 at 04:26
  • `ViewBag.Password.Length` This is used to send data to the View. On post-back you would have this null unless you have assigned values to it. Can you share the code of the full action? – Rahatur Mar 20 '20 at 04:34

1 Answers1

0

Generally viewbag is used to send data from controller to view. and you already have model property so why you need to check with the viewbag?.

For min and max length you can use data annotation and add attribute before the model property. it will be check at the ModelState.IsValid. you don't need to do extra code for that.

eg.

[MinLength(8,ErrorMessage = "Min length length should be 8"),MaxLength(250,ErrorMessage ="Max length should be 250")]
public string Password { get; set; }

you can also set regular expression for complex password as per you requirements.

Karan Ekkawala
  • 317
  • 1
  • 11