简体   繁体   English

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

[英]Handling ASP.NET MVC Routing in External JavaScript

What's the best way to avoid hardcoding URL's in JavaScript (primarily used when making AJAX calls)? 避免用JavaScript(主要是在进行AJAX调用时使用)对URL进行硬编码的最佳方法是什么?

In the past: 以往:

  1. Render JavaScript variable with result of @Url.Action or @Url.RouteUrl 使用@Url.Action@Url.RouteUrl结果呈现JavaScript变量
  2. Pass result of @Url.Action or @Url.RouteUrl to JavaScript in init/ctor. @Url.Action@Url.RouteUrl结果@Url.RouteUrl给init / ctor中的JavaScript。

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). 当然,这实际上是不可能的(JavaScript无法直接访问ViewContext,因此无法访问路由表)。

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? 但是我想知道是否有一种方法可以为JavaScript设置我自己的“路由表”,仅使用我知道需要的那些方法? (eg i set it up in the View) (例如我在视图中设置)

How do people handle this? 人们如何处理呢?

in-spite of injecting javascript in views i rather prefer - let HTML do its job and javascript do its. 尽管我更喜欢将JavaScript注入视图中-让HTML来完成其工作,而javascript来完成。 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. 这样,可以同时启用和禁用javascript两种类型的用户。

Same can be done for forms. 表单也可以这样做。

Implementing a Javascript routing engine wouldn't be too difficult. 实现Javascript路由引擎不会太困难。 First, serialize the Routes from C# to Javascript. 首先,序列化从C#到Javascript的路由。 Second, recreate the Url.Action method. 其次,重新创建Url.Action方法。

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. 我团队的项目始终呈现一个通用的Javascript变量,该变量包含所有必需的URL。
This approach ensures strongly-typed action methods and lends better to refactoring too. 这种方法可确保采取强类型的操作方法,并且也更适合重构。

This is easier said than achieved in practice, but your website should be fully functional with JavaScript turned off. 说起来容易做起来难,但是在关闭JavaScript的情况下,您的网站应该可以正常运行。 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. 完成此操作后,您应该能够在网站上添加AJAX支持,并在锚标签或FORM标签中重复使用现有的HREF属性。 The website will be easier to maintain as you won't need to update links in your JavaScript files. 该网站将更易于维护,因为您无需更新JavaScript文件中的链接。

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. 我决定实现自己的UrlFactory,直接在代码中使用ASP.NET帮助器(Html / Url),现在我没有src了,明天再发表。

Pros on this: I can track each and every url easily and perform some rewriting in a centralized fashion. 优点:我可以轻松跟踪每个URL并以集中方式执行一些重写。

Example of usage: 用法示例:

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

Then using 'em in javascript with 然后在javascript中使用'em

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. 一旦定义了自己的Factory,就可以劫持“重要的” URL(例如,用于重写),并将其保留给Url帮助器实现。

However for having this fully client side, there's an extra step of rendering a Js routing context, for accessing client side variables. 但是,为了拥有完整的客户端,还有一个额外的步骤就是呈现Js路由上下文,以访问客户端变量。

EDIT: As promised my very simple Url class builder: 编辑:如许诺我非常简单的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);
    }
}

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

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