在外部 JavaScript 中处理 ASP.NET MVC 路由

发布于 2024-12-11 13:09:17 字数 619 浏览 0 评论 0原文

避免在 JavaScript 中对 URL 进行硬编码(主要在进行 AJAX 调用时使用)的最佳方法是什么?

过去:

  1. 使用 @Url.Action@Url.RouteUrl 的结果渲染 JavaScript 变量,
  2. 传递 @Url.Action的结果>@Url.RouteUrl 到 init/ctor 中的 JavaScript。

有更好的办法吗?

最好做这样的事情:

var url = $.routes("actionName", "controllerName") // or "routeName" for named routes
$.post(url, { id = 1 }, function() { //.. });

这当然是不可能的(JavaScript 无法直接访问 ViewContext,因此无法访问路由表)。

但我想知道是否有一种方法可以为 JavaScript 设置我自己的“路由表”,只使用我知道需要的路由表? (例如我在视图中设置它)

人们如何处理这个问题?

What's the best way to avoid hardcoding URL's in JavaScript (primarily used when making AJAX calls)?

In the past:

  1. Render JavaScript variable with result of @Url.Action or @Url.RouteUrl
  2. Pass result of @Url.Action or @Url.RouteUrl to JavaScript in init/ctor.

Is there a better way?

It would be good to do something like this:

var url = $.routes("actionName", "controllerName") // or "routeName" for named routes
$.post(url, { id = 1 }, function() { //.. });

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).

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)

How do people handle this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

酒解孤独 2024-12-18 13:09:17

尽管我更喜欢在视图中注入 javascript - 让 HTML 完成它的工作,而 javascript 完成它的工作。下面是图案。

对于链接

/*A cssclass=ajaxlink is added to all those links which we want to ajaxify*/

//html in view
<a class='ajaxlink' href='@Url.Action("Action","Controller")'>I am An Ajax Link</a>

//generated clean html
<a class='ajaxlink' href='/controller/action'>I am An Ajax Link</a>


//Js


jQuery('.ajaxlink').live('click',function(e){
    e.preventDefault();    /*Prevent default behavior of links*/
    var url= $(e.target).attr('href');
   /*
          Now u have url, do post or get: 
          then append received data in some DOM element.
   */
});

//Controller

public ActionResult()
{
       if(Request.IsAjax())
       {    
            /*Return partial content*/
            return View(); 
       }
       else
       {
             return View("SomeOther_View.cshtml");

             /*
                At this point you may reject this request or return full view
                whatever you feel is okie.
             */
       }
}

这样两种类型的用户都可以处理启用 JavaScript 和禁用 JavaScript 的情况。

对于表格也可以这样做。

in-spite of injecting javascript in views i rather prefer - let HTML do its job and javascript do its. Below is the pattern.

For Links

/*A cssclass=ajaxlink is added to all those links which we want to ajaxify*/

//html in view
<a class='ajaxlink' href='@Url.Action("Action","Controller")'>I am An Ajax Link</a>

//generated clean html
<a class='ajaxlink' href='/controller/action'>I am An Ajax Link</a>


//Js


jQuery('.ajaxlink').live('click',function(e){
    e.preventDefault();    /*Prevent default behavior of links*/
    var url= $(e.target).attr('href');
   /*
          Now u have url, do post or get: 
          then append received data in some DOM element.
   */
});

//Controller

public ActionResult()
{
       if(Request.IsAjax())
       {    
            /*Return partial content*/
            return View(); 
       }
       else
       {
             return View("SomeOther_View.cshtml");

             /*
                At this point you may reject this request or return full view
                whatever you feel is okie.
             */
       }
}

This way both type of users can be handled javascript enabled and javascript disabled.

Same can be done for forms.

誰ツ都不明白 2024-12-18 13:09:17

实现 Javascript 路由引擎不会太困难。首先,将路由从 C# 序列化为 Javascript。其次,重新创建 Url.Action 方法。

然而,对于我从事过的任何项目来说,这都有点过大了。我团队的项目始终呈现一个通用的 Javascript 变量,其中包含所有必要的 URL。
这种方法确保了强类型的操作方法,并且也更适合重构。

Implementing a Javascript routing engine wouldn't be too difficult. First, serialize the Routes from C# to Javascript. Second, recreate the Url.Action method.

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.

波浪屿的海角声 2024-12-18 13:09:17

这说起来容易做起来难,但是您的网站应该在关闭 JavaScript 的情况下完全正常运行。实现此目标后,您应该能够向您的网站添加 AJAX 支持,并重新使用锚标记中的现有 HREF 属性或 FORM 标记中的操作属性。该网站将更易于维护,因为您无需更新 JavaScript 文件中的链接。

This is easier said than achieved in practice, but your website should be fully functional with JavaScript turned off. When this is achieved, you should be able to add AJAX support to your website and re-use existing HREF attributes in your anchor tags or action attributes in your FORM tags. The website will be easier to maintain as you won't need to update links in your JavaScript files.

硬不硬你别怂 2024-12-18 13:09:17

我决定实现我自己的 UrlFactory,在我的代码中直接使用 ASP.NET 帮助程序(Html/Url),现在我没有 src,明天我会发布它们。

优点:我可以轻松跟踪每个网址并以集中方式执行一些重写。

使用示例:

@{
  string myAjaxUrl = UrlFactory.GetUrl (ActionName, ControllerName, new { query-params });
}

然后在 javascript 中使用 'em 和

var jsUrl = '@myAjaxUrl';

一旦定义了自己的工厂,您就可以劫持“重要”url(例如用于重写),并为 Url 帮助器实现保留通用性。

然而,为了拥有这个完整的客户端,需要渲染 Js 路由上下文的额外步骤,以访问客户端变量。

编辑:正如我所承诺的,我非常简单的 Url 类生成器:

public static class UrlFactory
{
    public static string GetUrl(string Action, string Controller, object RouteValues)
    {
        UrlHelper Url = new UrlHelper(HttpContext.Current.Request.RequestContext);
        return Url.Action(Action, Controller, RouteValues);
    }

    // Common URLS for Denied et similars.
    public static string GetDeniedUrl(PEDUtenti Utente, object RouteValues)
    {
        return GetUrl(Utente, "Denied", "Errors", RouteValues);
    }
    public static string GetDeniedUrl(object RouteValues)
    {
        return GetUrl("Denied", "Errors", RouteValues);
    }
}

I've decided to implement my own UrlFactory, using ASP.NET helpers directly (Html/Url) in my code, now I don't have the src with me, I'll post'em tomorrow.

Pros on this: I can track each and every url easily and perform some rewriting in a centralized fashion.

Example of usage:

@{
  string myAjaxUrl = UrlFactory.GetUrl (ActionName, ControllerName, new { query-params });
}

Then using 'em in javascript with

var jsUrl = '@myAjaxUrl';

Once you've defined your own Factory, you can hijack "important" urls (eg. for rewriting), and leave common to the Url helper implementation.

However for having this fully client side, there's an extra step of rendering a Js routing context, for accessing client side variables.

EDIT: As promised my very simple Url class builder:

public static class UrlFactory
{
    public static string GetUrl(string Action, string Controller, object RouteValues)
    {
        UrlHelper Url = new UrlHelper(HttpContext.Current.Request.RequestContext);
        return Url.Action(Action, Controller, RouteValues);
    }

    // Common URLS for Denied et similars.
    public static string GetDeniedUrl(PEDUtenti Utente, object RouteValues)
    {
        return GetUrl(Utente, "Denied", "Errors", RouteValues);
    }
    public static string GetDeniedUrl(object RouteValues)
    {
        return GetUrl("Denied", "Errors", RouteValues);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文