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 >
<label asp-for="Id"></label>
<input asp-for="Id" />
</div>
<div >
<label asp-for="Name"></label>
<input asp-for="Name" />
</div>
<div >
<label asp-for="DOB"></label>
<input asp-for="DOB" />
</div>
<div >
<label asp-for="Role"></label>
<select asp-for="Role" asp-items="@new SelectList(Enum.GetNames(typeof(Role)))"></select>
</div>
<button type="submit" >Submit</button>
</form>
Firstly, a get method to invoke the Create() action method and fill some data:
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
so why the name still exists after the second request?
CodePudding user response:
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();
wwill resolve your issue completely.
CodePudding user response:
It can reset the data to which you have responded. So basically to send data without any loss