How to retain form data using JavaScript when model is not directly bind to html controls in ASP.Net Core
Tags: javascript, dotnetcore, dotnet, html
Published: 2023-10-02 08:03:27

There may be a situation when you have not directly bind the html controls to model in the asp.net core but you may need to retain the user data which user has filled in the form. Probably for the validation purpose at the backend and then redirect user to the same page. 

There is solution for that.

Look at the code below from the **Index.cshtml**:

```
@model MyProject.Models.UserModel

<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="GenerateOTP">

   <div class="col-sm-6 form-group mb-2 mb-sm-2">
     <label for="fullname">Full Name<span class="req">*</span> 
     </label>
     <input type="text" class="form-control" name="FullName" 
      id="fullname" placeholder="Enter your full name." required>
   </div>

   <div class="col-sm-6 form-group mb-2 mb-sm-2">
     <label for="dob">Date of Birth<span class="req">*</span>
     </label>
     <input type="Date" name="DOB" class="form-control" id="dob" 
     placeholder="" required>
   </div>

   <div>
     <input type="checkbox" id="terms" name="Terms" value="1" 
     required>
     <label for="terms">I accept all terms & conditions.
          <span class="req">*</span>
     </label>
   </div>
</form>

@if (ViewBag.ErrorMessage != null)
{
  <script type="text/javascript">
        document.getElementById('fullname').value = 
        "@Model.FullName"
        document.getElementById('dob').value = 
        "@Model.DOB.ToString("yyyy-MM-dd")"
        document.getElementById('terms').checked = true
  </script>
}
```
Above HTML controls are not bind to any model directly, hence validation takes place at the backend service and then in case of validation, user will be redirected to the same page. 

Below is the code of HomeController.cs

```
public IActionResult GenerateOtp([FromForm] UserModel userModel)
{
   var status = dbConnector.CheckCardStatus(userModel.Card, 
                _logger);
   if (status.Equals(CardEnum.Valid))
   {
     HttpContext.Session.SetObjectInSession("userData", userModel);    
   }
   else if (status.Equals(CardEnum.NotActivated))
   {
     userModel.ErrorMessage = "This card is not activated!";
     return RedirectToAction("Index", userModel);
   }
   else
   {
     userModel.ErrorMessage = "Invalid card number.";
     return RedirectToAction("Index", userModel);
    }
   return View();
}
```

**Flow is as follows:**
1) User enters the information in HTML controls which is not directly bound to models but data will be stored in the model.|
2) Upon clicking the submit button, model will be submitted to Home Controller.
3) Since action is GenerateOTP, GenerateOTP method will be called.
4) If data is valid then it is stored in session object. If not, model will be redirected to Index.cshtml along with error message.
5) Information present in the model will be inserted in respective HTML controls.

**Conclusion**: If HTML controls are used instead of ASP controls for some reason, you can still retain the user data and refill the information by directing to same page and display error to the user.