【发布时间】:2021-08-02 18:43:04
【问题描述】:
我刚开始使用 ASP .NET MVC。 我正在尝试使用 jQuery ajax 调用 POST 操作方法,如下所示,但我的 Controller 方法没有被命中。 下面的js函数由按钮的onclick()调用。
function ValidateLogin() {
var dat = {};
dat.Username = $("#username_input").val();
dat.Password = $("#password_input").val();
dat.PreviousActionName = '';
if (dat.Password != '' && dat.Username != '') {
$.ajax({
url: '/Login/ValidateLogin', //Tried '@Url.Action("ValidateLogin", "Login")' as well
type: 'POST',
data: JSON.stringify(dat),
contentType: 'application/json',
dataType: 'json',
success: function () {
alert("Success!");
},
error: function (xhr, status, error) {
var err = xhr.responseText;
alert("Failed");
}
});
}
}
这是我的登录模型
public class LoginModel
{
public String Username { get; set; }
public String Password { get; set; }
public String PreviousActionName { get; set; }
}
和登录控制器:
public class LoginController : Controller
{
// GET: Login
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult ValidateLogin(LoginModel loginModel)
{
String Username = loginModel.Username;
String Password = loginModel.Password;
return View("Login");
}
}
注意:我在 IIS 中本地托管此项目,名称为“客户端”。 所以初始 URL 将是 http://localhost/Client 当我在 AJAX url 中使用“/Login/ValidateLogin”时,最终 URL 是 http://localhost/Login/ValidateLogin,在这种情况下,我在浏览器控制台中找不到 http://localhost/Login/ValidateLogin。所以我将 ajax 中的 url 更改为“Client/Login/ValidateLogin”。现在它只是ajax中的错误函数。
如果有帮助,这是我的 RouteConfig 类:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Login", id = UrlParameter.Optional }
);
}
}
我做错了什么。请帮忙! 提前致谢。
【问题讨论】:
-
“现在它只是 ajax 中的错误函数。” - 如果你检查它的参数,“错误函数” 可能会告诉你问题而不是仅仅提醒“失败”。
-
@Andreas 我在浏览器中调试过。错误函数的所有参数都是'undefined'。
-
如果 jQuery 触发了
error回调,那么它们都不会是undefined -
对不起,我该怎么做?
标签: c# jquery ajax asp.net-mvc