【问题标题】:How to implement ASP.NET Core MVC AJAX requests using jQuery如何使用 jQuery 实现 ASP.NET Core MVC AJAX 请求
【发布时间】:2020-08-24 17:50:05
【问题描述】:

我在 asp.net webforms 和 jquery ajax 工作多年,现在想使用相同的前端技术 jQuery Ajax 在 asp.ner 核心中实现一个项目。

【问题讨论】:

标签: jquery ajax asp.net-core asp.net-web-api


【解决方案1】:

jQuery 实现在多个平台上是相同的。你可以使用类似的代码。

jquery ajax 示例:

$.ajax({
          type: 'POST',
          url: '/controller/Action'
          data: { parameter1 : 'value', parameter2 : 'value' },
          success: function (response) {
                       // code on successful completion
                   }
          error: function (response) {
                     // code on failure
                 }
});

【讨论】:

  • 这应该是最受接受的答案。简洁明了,没有任何错误代码。
【解决方案2】:

您可以应用内联data-ajax-* 属性如下:

包含 jquery 库:

@section Scripts {
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-ajax-unobtrusive@3.2.6/dist/jquery.unobtrusive-ajax.min.js"></script>
}

将 data-ajax 属性应用于锚元素:

<!-- ajax content will load inside this div -->
<div id="data-div"></div>

<a href="#" 
    data-ajax="true" 
    data-ajax-mode="replace" 
    data-ajax-update="#data-div" 
    data-ajax-loading="#loading"
    data-ajax-url="@Url.Page("Index", "ServerDate")">Run Ajax Request</a>

<!-- spinning loading indicator -->
<span id="loading" style="display:none;"> <i class="fas fa-spinner fa-spin"></i></span>

和后端方法:

public class IndexModel : PageModel
{
    public void OnGet() { }

    public ContentResult OnGetServerDate()
    {
        return Content($"{DateTime.Now}");
    }
}

同样的属性也可以应用于表单。

在此处查看演示:http://demo.ziyad.info/en/AjaxRequest

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 2010-10-14
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多