使用Jquery AJAX调用的路由行为,MVC
您好,我正在尝试解决如何进行jQueryAjax调用,但我不明白为什么我的路由没有按预期进行 我的路线很标准使用Jquery AJAX调用的路由行为,MVC,jquery,ajax,asp.net-mvc,routing,Jquery,Ajax,Asp.net Mvc,Routing,您好,我正在尝试解决如何进行jQueryAjax调用,但我不明白为什么我的路由没有按预期进行 我的路线很标准 public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "
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个Home,但是我仍然会得到奇怪的结果,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"}}}}
对这种行为感到困惑您在AJAX调用中缺少了一个斜杠。你一定是在我前面划了一道斜线 家 url值中的控制器 因此,您的代码必须如下所示:
$.ajax({
url : "/Home/TestPost",
type: "POST",
cache: false
});
始终使用@Url.Action(…)
生成您的Url(这将正确生成/Home/TestPost
)