0
我已經在mvc route.config中聲明瞭自定義路由,它是爲獲取動詞而工作,但不適用於動詞後。 我想使用jquery調用post動詞,但它不起作用。MVC自定義路由不適用於在MVC郵政調用
你能幫我解決這個問題嗎?
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>
當我運行該程序,並按下按鈕,下面的錯誤出現:
假設'MyController'是區域名稱,嘗試使用此'MapRoute':'routes.MapRoute( 「默認」, 「myController的/ {控制器}/{行動} /(編號)」,新的{控制器=「Post」,Action =「index」,id = UrlParameter.Optional});'。使用AJAX的JSON POST似乎很有用,但它沒有找到由'url'給出的操作方法的路徑路徑。 –