在 .Net Core 3.1 上发布时未使用新的 ViewModel 重新加载表单

Form not reloaded with new ViewModel when posting on .Net Core 3.1

我试图在调用 post 方法后更改屏幕上的值。似乎甚至使用 ModelState.Clear();方法添加它仍然没有反映在屏幕上的新值。请注意,我正在使用 jQuery Unobtrusive AJAX v3.2.6 库。

请在下面查看我的剃须刀页面和控制器代码。

@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>

控制器

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);
}

由于你使用了unobtrusive ajax,所以它会return局部视图的html代码,但不会刷新你想要的局部view.If刷新局部视图,你可以尝试用数据替换html代码-ajax-complete.Here是一个工作演示:

控制器:

 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);
        }

查看:

@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>
}

_局部视图:

@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>

结果: