我对 ASP.NET MVC 还很陌生,我希望这不是一个太愚蠢的问题。所以它来了。
我有...
- 一个 ASP.NET MVC 应用程序,其域类似于 http://mydomain/mysubfoler1/myappfolder
我的问题...
- 我的应用程序的路由(它运行良好,无需在域名后使用子文件夹)。应用程序主页加载得不错,有 css 文件,但没有图像等资源(在 css 文件中定义),并且没有类似于 /mycontroller/myaction 的 jQuery ajax 调用
- 链接只能使用一次(我第二次收到与此链接类似的页面:http://mydomain/mysubfoler1/myappfolder/myController/myController/myAction)
- jquery ajax 调用不起作用。 (我在脚本文件夹中有额外的 js 文件,它们正在调用多个 Controller 操作。p.e.
$.getJSON("../mycontroller/myaction/" + id, function(figure) {
// do something
});
这是我的包含路由的Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "myController", action = "Index", id = "" }
defaults
);
routes.MapRoute(
"Root",
"",
new { controller = "myController", action = "Index", id = "" }
);
}
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MyApplicationWeb.LocalizationWebFormViewEngine());
RegisterRoutes(RouteTable.Routes);
//RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
}
有什么建议吗?我的第一个建议是使用以下区域:
"mysubfolder1/myappfolder/{controller}/{action}/{id}"
(但没有任何运气)
非常感谢您的帮助!
最佳答案
...css files but without ressources like images (defined in css files) and without jQuery ajax calls similar to /mycontroller/myaction
您需要编辑所有 jQuery/CSS 图像链接或 URL。 ASP.NET MVC 路由仅适用于传入的 Web 请求,并且由于您的 css 文件是静态的,因此使用 background-image: url('../images/background.png')
引用的任何图像将相对于 css 文件所在的文件夹。
正如其他答案所述,在任何 View
中(.ascx 和 .aspx 文件),使用 <%= Url.Action("ActionName") %>
根据您的路由生成正确的 URL。同样,使用<%= Url.Content("~/folder/something.png") %>
为 Web 服务器上的任何内容(图像、CSS、JS 等)生成链接。
但是,您不能在 .css 和 .js 文件中使用它们,因为它们不是使用 ASP.NET WebForms View 引擎进行解析的。
<小时/>根据评论更新:
由于 ASP.NET 不负责提供静态文件,如 .css
和.js
,您需要对文件中的操作/ Controller 的 URL 进行硬编码。
另一种可能比较困惑的方法是将字符串放入 .css
中/.js
可以很容易区分的文件(例如: {someAction}
)而不是实际的 URL,然后制作任何 .css
或.js
文件链接指向 action
在controller
上。然后,该操作将获取适当的文件,用适当的 URL 替换其中的所有字符串,然后将其输出回用户。然后,您将使用以下内容来提供文件
return Content(fileText, "text/css"); // or "text/javascript"
另一种方法是将任何 css/js 放置在单独的 View 中(没有母版页),这样您就可以使用 Html 和 Url Helpers。然后,您只需使用正确的代码返回适当的 View 即可提供这些文件。注意:请确保设置正确的 ContentType,请参阅 ASP.NET MVC and text/xml content type
关于jquery - 路由域子文件夹问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2530612/