I am trying to change the value on a screen after calling a post method. It seems even with the ModelState.Clear(); method added it still does not reflect the new value on the screen. Note that I am using jQuery Unobtrusive AJAX v3.2.6 library.
Please see my razor page and controller code below.
@model TestApp.ViewModels.EmployeeViewModel
<form method="post"
data-ajax="true"
data-ajax-method="post"
data-ajax-url="@Url.Action("Detail", "Employee")">
<input asp-for="EmployeeFirstName" />
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Controller
public IActionResult Detail()
{
EmployeeViewModel employeeViewModel= new EmployeeViewModel ();
employeeViewModel.EmployeeFirstName = "John";
return View(employeeViewModel);
}
[HttpPost]
public IActionResult Detail(EmployeeViewModel employeeViewModel)
{
employeeViewModel.EmployeeFirstName = "Brian";
ModelState.Clear();
return View(employeeViewModel);
}
CodePudding user response:
Since you use unobtrusive ajax,so it will return the html code of the partial view,but it will not refresh the partial view.If you want to refresh the partial view,you can try to replace the html code with data-ajax-complete.Here is a working demo:
Controller:
public IActionResult Detail()
{
EmployeeViewModel employeeViewModel = new EmployeeViewModel();
employeeViewModel.EmployeeFirstName = "John";
return View(employeeViewModel);
}
[HttpPost]
public IActionResult Detail(EmployeeViewModel employeeViewModel)
{
employeeViewModel.EmployeeFirstName = "Brian";
ModelState.Clear();
return PartialView("~/Views/_Partial.cshtml", employeeViewModel);
}
View:
@model WebApplication107.Models.EmployeeViewModel
<div class="row main-section-border">
<div id="div1" class="col-sm-12">
@{
await Html.RenderPartialAsync("~/Views/_Partial.cshtml", Model);
}
</div>
</div>
@section scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.js"></script>
<script>
completed = function (xhr) {
$("#div1").html(xhr.responseText);
};
</script>
}
_Partial view:
@model WebApplication107.Models.EmployeeViewModel
<form method="post"
data-ajax="true"
data-ajax-method="post"
data-ajax-url="@Url.Action("Detail", "Test")"
data-ajax-complete="completed"
>
<input asp-for="EmployeeFirstName" />
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Result: