user16276760
user16276760

Reputation:

why post method doesn't refresh the page in the action method?

I know the post action method below is anti-pattern, but still I assume to see a new page with Name being set to null. But when I click the submit button, the page is not reloaded and I still see the old name displayed, is this a browser thing or asp.net core framework thing?

public class HomeController : Controller
{
   private IRepository repository;
   public HomeController(IRepository repo)
   {
      repository = repo;
   }

   // ...

   public IActionResult Create()  // create a Employer that has a name in the browser
   {
      return View();
   }

   [HttpPost]
   public IActionResult Create(Employee model)
   {
      model.Name = "";   // <----------------set it to null so I expect to see the Name being empty in the reponse
      return View(model);  
   }
}

// view file, Create.cshtml:

@model Employee
@{
    ViewData["Title"] = "Create Employee";
}

<h2>Create Employee</h2>

<form asp-action="Create" method="post">
    <div class="form-group">
        <label asp-for="Id"></label>
        <input asp-for="Id" class="form-control" />
    </div>
    <div class="form-group">
        <label asp-for="Name"></label>
        <input asp-for="Name" class="form-control" />
    </div>
    <div class="form-group">
        <label asp-for="DOB"></label>
        <input asp-for="DOB" class="form-control" />
    </div>
    <div class="form-group">
        <label asp-for="Role"></label>
        <select asp-for="Role" class="form-control" asp-items="@new SelectList(Enum.GetNames(typeof(Role)))"></select>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Firstly, a get method to invoke the Create() action method and fill some data:

enter image description here

After clicking submit button, the page still shows the original name where I exepct to see a empty name since I modify it in the post action method

enter image description here

so why the name still exists after the second request?

Upvotes: 0

Views: 312

Answers (1)

Md Farid Uddin Kiron
Md Farid Uddin Kiron

Reputation: 22447

So why the name still exists after the second request?

Well, altough, you have rebind your model property value. However, your current model state still remain unchanged. Therefore, you are getting the older value even after the form resubmission. To overcome this issue, please try following code snippet:

Solution:

You have clear your current model state by using ModelState.Clear(); method before assigning the new value. So, your create method should be as bellow:

        [HttpPost]
        public IActionResult Create(Employee model)
        {
            ModelState.Clear();
            model.Name = "";  
            return View(model);
        }

Note: Rest of the code will remain unchanged.

Output:

enter image description here

ModelState.Clear(); wwill resolve your issue completely.

Upvotes: 0

Related Questions