【问题标题】:update part of the page after unobtrusive ajax post on Razor Pages在 Razor 页面上不显眼的 ajax 发布后更新页面的一部分
【发布时间】:2021-03-27 13:33:23
【问题描述】:

我有一个表单的 Razor 页面。它发布数据并设置一些状态消息。发布是通过 ajax 不显眼的方式完成的。但是,以这种方式状态消息永远不会出现在页面上。请您指导我如何在 Razor Pages 上完成此更新?

HTML 部分

<form method="post" asp-controller="Home" asp-action="Index" data-ajax="true" data-ajax-loading="#loading">
   <div class="form-group">
        <input id="code" asp-for="Code" type="text" class="form-control"/>
    </div>
    <button type="submit" class="btn btn-primary">Check</button>
</form>

// I need to update this part
<div class="result">
    Result
    <span class="message">@Model.CheckMessage</span>
</div>

后端部分

    public class IndexModel : PageModel
    {
     
        [Required]
        [BindProperty]
        public string Code { get; set; }

        public string CheckMessage { get; set; }

        public async Task<IActionResult> OnPostAsync()
        {
          this.CheckMessage = "Test"; // how to make this work
          return Page();
        }

【问题讨论】:

    标签: ajax asp.net-core post razor-pages


    【解决方案1】:

    首先,您需要使用data-ajax-update 来更新来自服务器的响应。

    那么,服务器的响应不应该是return Page(),这会给出整个页面的html,你想要的只是&lt;span class="message"&gt;@Model.CheckMessage&lt;/span&gt;。所以你需要创建一个局部视图。

    按照以下步骤操作:

    • Pages/Shared 文件夹中创建一个名为_Partial.cshtml注意:剃刀视图而不是剃刀页面)的局部视图:

      @model IndexModel
      <span class="message">@Model.CheckMessage</span>
      
    • 如下更改您的剃须刀页面:

                           //add data-ajax-url and data-ajax-update.....
      <form method="post" data-ajax-url="Index" data-ajax="true" data-ajax-update="#result" data-ajax-loading="#loading">
           <div class="form-group">
               <input id="code" asp-for="Code" type="text" class="form-control" />
           </div>
           <button type="submit" class="btn btn-primary">Check</button>
      </form>
      <div id="result">       //change class to id....
           Result
       </div>
      
       @section scripts{
           <script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.min.js"></script>
       }
      
    • 后端:

      [Required]
      [BindProperty]
      public string Code { get; set; }
      
      [ViewData]
      public string CheckMessage { get; set; }
      
      public async Task<IActionResult> OnPostAsync()
      {
           this.CheckMessage = "Test"; 
           return new PartialViewResult
           {
               ViewName = "_Partial",
               ViewData = this.ViewData
           };
      }
      

    结果:

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 2020-12-24
      相关资源
      最近更新 更多