asp.net mvc的阿贾克斯后返回404未找到 [英] asp.net mvc ajax post returns 404 not found
问题描述
我试图做使用jQuery AJAX功能的Ajax请求。我有一个很奇怪的行为。我的文件夹结构IST是这样的:
I'm trying to do an ajax request using jquery ajax function. I have a very strange behaviour. My folder structure ist like this:
我的客户端Ajax调用(在UserManagement / Index.cshtml)如下所示:
My client-side ajax call (in UserManagement/Index.cshtml) looks like the following:
var rolename = viewModel.roleName();
$.ajax({
type: "POST",
url: '@Url.Action("AddRole", "UserManagement")',
contentType: "application/json; charset=utf-8",
data: { rolename: rolename },
success: function(data) {
var role = new Role(rolename);
model.addRole(role);
model.appendItem("#accordion", role.getItem());
viewModel.roleName("");
}
});
在我UserManagementController.cs我有下列行为:
In my UserManagementController.cs I have the following actions:
// GET: /UserManagement/
public ActionResult Index()
{
var serializer = new JavaScriptSerializer();
var context = new ApplicationDbContext();
var users = context.Users.ToList();
var roles = context.Roles.ToList();
ViewBag.Users = users;
ViewBag.Roles = roles;
return View();
}
//
// POST: /UserManagement/AddRole
[HttpPost]
public string AddRole(string rolename)
{
Response.StatusCode = 200;
return "gsfgdg";
}
我已经尝试过使用GET而不是POST或更改AddRole为void类型和任何其他,但我不能得到这个工作。我总是收到404未找到。
任何人可以帮助?
I already tried to use a GET instead of POST or to change AddRole to void type and anything other but I can't get this to work. I always receive a "404 not found". Can anybody help?
在此先感谢!
推荐答案
如果您删除的Content-Type的情况下正常工作。
Your case will work if you remove Content-Type.
案例1:如果我们使用的Content-Type:应用/ JSON
Case 1: If we use Content-Type: "application/json"
当您使用的应用程序/ JSON的内容类型,在服务器端请求ScriptServices预计数据作为JSON序列串。
When you request with a Content-Type of application/json, in server side ScriptServices expects data as JSON serialized string.
不过,我们可以看到无效的JSON原始***
通常的结果进行回应。
However, we can see "Invalid JSON primitive ***"
is usually the result in response.
在这里,我们应该明白要通过jQuery的数据选项为{'参数':'值'},而不是{'参数':'值'}
Here we should understand to pass the jQuery's "data" option as "{'param':'value'}", not {'param':'value'}.
所以你的情况,实现了解决方案:我们需要提供数据
如下
So in your case, to achieve the solution: we need to supply data
as below
var rolename = viewModel.roleName();
$.ajax({
type: "POST",
url: '@Url.Action("AddRole", "UserManagement")',
contentType: "application/json; charset=utf-8",
data: "{ 'rolename':'" + rolename +"' }",
success: function(data) {
var role = new Role(rolename);
model.addRole(role);
model.appendItem("#accordion", role.getItem());
viewModel.roleName("");
}
});
案例2:如果我们跳过内容类型:应用/ JSON
Case 2: If we skip Content-Type: "application/json"
我们应该提供jQuery的数据选项,JSON对象{'参数':'值'}或{参数:'值'}。 (像你一样)
We should supply jQuery's "data" option as JSON object {'param':'value'} or {param:'value'}. (as you did)
希望它能帮助:)
这篇关于asp.net mvc的阿贾克斯后返回404未找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!