简体   繁体   English

从MVC Razor视图(而非Index.cshtml)调用时,Ajax调用失败

[英]Ajax call fails when called from MVC Razor view other than Index.cshtml

I am confused on why my Ajax call succeeds when called from an Index view but fails when called from a view with a different name. 我对为什么从索引视图中调用我的Ajax调用成功而从具有不同名称的视图中调用却失败的原因感到困惑。 I have an ASP .NET MVC 4 project that also involves some Ajax requests via Javascript. 我有一个ASP .NET MVC 4项目,该项目还涉及通过Javascript进行的一些Ajax请求。 My Javascript/JQuery code for this page is complex enough that I have written them in a separate Javascript file. 我在此页面上的Javascript / JQuery代码非常复杂,以至于我已将它们编写在单独的Javascript文件中。 Here is a simplified extract from one of my Javascript files where I make an Ajax request: 这是我发出Ajax请求的Javascript文件之一的简化​​摘录:

//to be called in the JQuery page load function
function initialize(){
    $.ajax({ url: MyController/GetData, async: false })
        .done(function(returnedData) {
            doStuff(returnedData);
        });
}

In my Home controller, I created a new View with the default name Index.cshtml . 在我的Home控制器中,我创建了一个默认名称为Index.cshtml的新View。 In this view, I referenced the external Javascript file tha contains the above function. 在此视图中,我引用了包含上述功能的外部Javascript文件。 When I open my /Home page (which is Home/Index because I have default routing setup), the initialize() function is called and the Ajax call succeeds as expected. 当我打开/Home页面时(因为我具有默认的路由设置,所以它是Home/Index ),将调用initialize()函数,并且Ajax调用将按预期成功

I created another View called Details.cshtml and in this page, I also referenced the same Javascript file. 我创建了另一个名为Details.cshtml视图,并且在此页面中,我还引用了相同的Javascript文件。 When I open my /Home/Details page, the initialize() function is called and the Ajax call fails . 当我打开/Home/Details页面时,将调用initialize()函数,而Ajax调用将失败 The error message says it was looking for /Home/Details/MyController/GetData which definitely does not exist. 错误消息说它正在寻找/Home/Details/MyController/GetData ,它肯定不存在。

The wierdness is that this same call works from one page and doesnt work from another. 奇怪的是,同一呼叫只能在一个页面上工作,而不能在另一页面上工作。 My questions: 我的问题:

  1. Can someone offer an explanation as to why this is happening? 有人可以解释为什么会这样吗?
  2. Is there any remedy for it? 有什么补救办法吗?

Also, note that I have read a couple of questions regarding calling Ajax from MVC Razor view and they often suggest that you use the Url.Action(...) to create the URL's. 另外,请注意,我已经阅读了一些有关从MVC Razor视图调用Ajax的问题​​,它们通常建议您使用Url.Action(...)创建URL。 The problem is that in this case, this is not an option for me as I really want to separate my Javascript from my Razor View. 问题是在这种情况下,这对我来说不是一个选择,因为我真的想将我的Javascript与我的Razor View分开。 Also, if this was such a hinderance, why does it work when called from the Index page? 另外,如果这是一个障碍,那么为什么从“索引”页面调用它时仍然有效?

Thank for your help. 谢谢您帮忙。

UPDATE: Here is the RouteConfig file: 更新:这是RouteConfig文件:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("favicon.ico");

        routes.MapRoute(
            name: "Default", 
            url: "{controller}/{action}/{id}",
            defaults:new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
    }
}

Note: This behavior doesnt just happen when I am on Home/Index or Home/Details . 注意:当我在Home/IndexHome/Details上时,不会仅发生此行为。 I have noticed that the Ajax call works fine from AnyController/Index page, but fails when called from AnyController/AnyOtherPage . 我注意到Ajax调用可以从AnyController/Index页面正常工作,但是从AnyController/AnyOtherPage调用时失败。

It depends on your routing, but try this (put a slash in front of MyController): 这取决于您的路由,但是请尝试以下操作(在MyController前面加一个斜杠):

function initialize(){
    $.ajax({ url: /MyController/GetData, async: false })
        .done(function(returnedData) {
            doStuff(returnedData);
        });
}

It can also help to specify if it is a get or a post, and the datatype you want it to send as. 它还可以帮助指定它是get还是post,以及您希望其发送为的数据类型。 Mvc is good with Json: Mvc与Json很好:

function initialize(){
    $.ajax({ url: /MyController/GetData, async: false, dataType:"json", type:"Get" })
        .done(function(returnedData) {
            doStuff(returnedData);
        });
}

The reason it works on the index page could be because details must show in the url, but index does not. 它在索引页面上起作用的原因可能是因为详细信息必须显示在url中,但索引没有显示。 So if your index url is Home/Index, Home/ still works. 因此,如果您的索引URL是Home / Index,则Home /仍然有效。 For details it must show as Home/Details. 有关详细信息,它必须显示为“主页/详细信息”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM