您好,我正在尝试弄清楚如何进行Jquery ajax调用,但我不明白为什么我的路由没有按预期进行。
我的路由非常标准
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
在这里我调用控制器操作
[HttpPost]
public ActionResult TestPost(string teststring)
{
return Json("test");
}
这是我的Ajax电话
$(document).ready(function (){
/* attach a submit handler to the form */
$("#input").submit(function (event) {
/* stop form from submitting normally */
event.preventDefault();
alert('in the ajax');
teststring = 'tested string';
// check form is valid
if ($("#input").valid()) {
//ajax call!
$.ajax({
url : "Home/TestPost",
type: "POST",
cache: false
});
}
else { return false }
但是当我运行此调用时,它似乎没有在输出窗口中路由到Home / Testpost,它似乎正在向Home / Home / TestPost进发
{"ver":2,"id":"ZjW6WxGC8Yg=","name":"POST Home/Home","duration":"00:00:00.0290000","success":false,"responseCode":"404","url":"http://localhost:20064/Home/Home/TestPost"
所以我决定从url中删除Home,因此我没有得到其中的2个,但是仍然得到奇怪的结果,Testpost / Index
ver":2,"id":"cfAk091y/V8=","name":"POST TestPost/Index","duration":"00:00:00.0100000","success":false,"responseCode":"404","url":"http://localhost:20064/TestPost","properties":{"DeveloperMode":"true"}}}}
对此行为感到困惑
答案 0 :(得分:0)
您在AJAX调用中缺少一个斜杠。您必须在
前面加斜杠首页
URL值中的控制器。
所以您的代码必须是这样的:
$.ajax({
url : "/Home/TestPost",
type: "POST",
cache: false
});