我在mvc中的route.config中声明了自定义路由,它适用于获取动词,但不适用于动词。 我试图使用jquery调用post动词,但它不起作用。
你能帮我解决这个问题。
Route.config:
routes.MapRoute("Defualt", "MyController", new { Controller = "Post", Action = "index", id=UrlParameter.Optional });
Controller.cs:
public class PostController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
//[Route("Mycontroller/Post")]
public JsonResult AjaxMethod(string name)
{
PersonModel person = new PersonModel
{
Name = name,
DateTime = DateTime.Now.ToString()
};
return Json(person);
}
}
Index.cshtml:
@model MvcWithJquery.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="Get Current Time" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "MyController/Post/AjaxMethod",
data: '{name: "' + $("#txtName").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>
当我运行程序并按下按钮时,出现以下错误:
答案 0 :(得分:0)
在你的路线中:
routes.MapRoute("Defualt", "MyController", new { Controller = "Post", Action = "index", id=UrlParameter.Optional });
第二个参数是url
模式,您已将其定义为MyController
。因此,唯一可以访问此路由的网址是/MyController
。
因此,要使其工作,您需要将AJAX调用更改为正确的URL ...
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="Get Current Time" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "MyController",
data: '{name: "' + $("#txtName").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>
...或者,您需要更改URL以匹配您的AJAX调用。
routes.MapRoute("Defualt", "MyController/Post/{action}", new { Controller = "Post", action = "index", id=UrlParameter.Optional });
另外,在路线中有一个无法通过网址接受id
的可选{id}
参数没有多大意义。
routes.MapRoute("Defualt", "MyController/Post/{action}", new { Controller = "Post", action = "index" });