处理ASP.NET MVC路由在外部JavaScript [英] Handling ASP.NET MVC Routing in External JavaScript
问题描述
什么是硬编码避免在JavaScript中的URL(AJAX调用时主要使用)?最好的办法
What's the best way to avoid hardcoding URL's in JavaScript (primarily used when making AJAX calls)?
在过去的:
- 渲染JavaScript变量与
@ Url.Action结果
或@ Url.RouteUrl
-
@ Url.Action
或@ Url.RouteUrl
来的JavaScript在初始化/构造函数的通过结果。
- Render JavaScript variable with result of
@Url.Action
or@Url.RouteUrl
- Pass result of
@Url.Action
or@Url.RouteUrl
to JavaScript in init/ctor.
有没有更好的办法?
这将是很好的做这样的事情:
It would be good to do something like this:
var url = $.routes("actionName", "controllerName") // or "routeName" for named routes
$.post(url, { id = 1 }, function() { //.. });
这当然不是真的有可能(JavaScript没有直接访问到ViewContext,因此不能够访问路由表)。
Which of course isn't really possible (JavaScript doesn't have direct access the to the ViewContext and thus doesn't have access to the route tables).
但我不知道是否有一种方法可以让我这种设置我自己的路由表对JavaScript的,只有我知道这将需要的人? (例如我设置它在视图)
But i'm wondering if there's a way i can kind of setup my own "route table" for JavaScript, with only the ones i know it would need? (e.g i set it up in the View)
人们如何处理?
推荐答案
实现一个Javascript路由引擎不会太困难。首先,从序列C#的路线为JavaScript。其次,重新创建 Url.Action
方法。
Implementing a Javascript routing engine wouldn't be too difficult. First, serialize the Routes from C# to Javascript. Second, recreate the Url.Action
method.
不过,这对任何我制作的项目有点大材小用。我的团队的项目一直呈现包含所有必要的URL的一个常见的JavaScript变量。结果
这种方法确保强类型的操作方法,并赋予更好地重构了。
However, that's a bit overkill for any of the projects I've worked on. My team's projects have always rendered a common Javascript variable that holds all necessary URL's.
This approach ensures strongly-typed action methods and lends better to refactoring too.
这篇关于处理ASP.NET MVC路由在外部JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!