作者:StormyXin | 来源:互联网 | 2023-02-05 21:55
抱歉发布.我在这里看到了很多答案以及这篇很棒的帖子,但是我的电话仍然没有用.以下是我的配置:
路线配置
routes.MapRoute(
name: "MyRoute",
url: "{controller}/{action}/{id}/{name}/{age}",
defaults: new { cOntroller= "Home", action = "MyAction"
, id = UrlParameter.Optional
, name = UrlParameter.Optional
, age = UrlParameter.Optional}
);
家庭控制器中的动作方法
[HttpGet]
public ActionResult MyAction(int id, string name, int age)
{
// Do some work and return View()
}
我的Javascript代码
function MyFunction(id)
{
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
"id": id,
"name": name,
"age": age
},
// url: '@Url.Action("MyAction", "Home")',
url: '/Home/MyAction',
success: function (response) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
}
这段代码可能会失败......它总是会进入error
并且警报框始终显示错误.它永远不会用于控制器的MyAction
操作,Home
无论我用户的格式如何url
.
这是怎么回事 ?
1> kazem..:
当您创建get请求时,您没有任何数据请求,您只能使用查询字符串,而不能使用Body数据
function MyFunction(id)
{
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
//data: {
// "id": id,
// "name": name,
// "age": age
//},
// url: '@Url.Action("MyAction", "Home")',
url: '/Home/MyAction/'+id+'/'+name+'/'+age,
success: function (response) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
}
@ Bloomberg58,你的动作mehtod中的代码是什么?我认为你必须使用"return Json(model,JsonRequestBehavior.AllowGet);"