【发布时间】:2019-03-12 12:23:52
【问题描述】:
所以我知道我们可以使用 $.ajax() 进行 ajax 请求,但是在 ASP.NET Core 中,我们应该能够使用标签助手通过表单本身轻松地发出 ajax 请求。我发现这个网站解释了如何做到这一点。
https://dotnetthoughts.net/jquery-unobtrusive-ajax-helpers-in-aspnet-core/
但是。当我提交表单时,它会重定向页面,而不仅仅是执行 ajax 请求。
这就是我所做的:
- 我创建了一个新的 ASP.NET Core Web 应用程序
- 选择的 MVC 类型
- 通过 NuGet 添加了 Microsoft.jQuery.Unobtrusive.Ajax 包
- 添加了新的 MVC 控制器 (Controllers/LoginController.cs)
- 添加了新视图 (Views/Login/Index.cshtml)
- 在 _layout.cshtml 中添加了脚本
这些是我创建/修改的文件的内容
查看/登录/Index.cshtml:
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<form asp-controller="Login" asp-action="SaveForm"
data-ajax-begin="onBegin" data-ajax-complete="onComplete"
data-ajax-failure="onFailed" data-ajax-success="onSuccess"
data-ajax="true" data-ajax-method="POST">
<input type="submit" value="Save" class="btn btn-primary" />
</form>
<script>
var onBegin = function () {
alert("Begin");
};
var onComplete = function () {
alert("Complete");
};
var onSuccess = function(context){
alert(context);
};
var onFailed = function(context){
alert(context);
};
</script>
控制器/LoginController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace AspTest.Controllers
{
public class LoginController : Controller
{
public IActionResult Index()
{
return View();
}
// I also tried making this async, but this didn't help
public IActionResult SaveForm()
{
return Json(new { test = "this is a test" });
}
}
}
我在 Views/Shared/_Layout.cshtml 中更改的部分
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
</environment>
(添加了两个 jquery-validation 脚本)
我想在不刷新页面的情况下更新页面内容。例如,当用户尝试使用不正确的凭据登录而不刷新整个页面时显示错误消息。
我对 ASP.NET 完全没有经验,所以我可能只是遗漏了一些明显的东西。
编辑: 值得指出的是,页面重定向时,会重定向到/Login/SaveForm,并显示正确的数据。
【问题讨论】:
-
将
[HttpPost]属性添加到您的SaveForm()方法中。 -
@GaganDeep 刚刚试过。不幸的是,这不起作用
-
检查您的浏览器控制台是否在提交表单时出错。
-
@GaganDeep 没有错误。只有200响应。我添加了一些编辑以更清楚地了解当前正在发生的事情
-
你能不能把你的 onsuccess 方法的名字改成 onsuccesscall 或者别的。我知道这个建议是有线的,但如果我没记错的话,它曾经发生在我身上。
标签: c# asp.net-core