【问题标题】:How to convert url.HttpRouteUrl to a normal string url?如何将 url.HttpRouteUrl 转换为普通字符串 url?
【发布时间】:2016-05-18 14:32:20
【问题描述】:

我继承了一些代码,我正在尝试找出 webapi 控制器的正确 url,但是我缺乏 mvc web api 的知识。

我有一个内联脚本,它正在制作这样的 ajax 帖子:

$('#saveNewEducation').on('click', function () {
    var educationAdd = {
        'educationId': $('#newEducation').val(),
        'startDate': $('#newEducationDate').val(),
        'identificationId': $('#identificationId').val(),
        'educationNote': $('#newEducationNote').val(),
        'examinerId': $('#newExaminer').val()

    };
    $.post('@Url.HttpRouteUrl("DefaultApi", new { controller = "EmployeeApi", educationName = "educationCreate" })', educationAdd)
        .done(function (data, textStatus, jqXhr) {
            if (jqXhr.status == 200) {
                $('#save-education').modal('show');

            } else {
                $('#fail-save-employee').modal('show');
            }

        })
        .fail(function (jqXhr) {
            var education = $("#new-education");
            if (jqXhr.status == 409) {
                $('#future-save-employee').modal('show');
            } else {
                if (jqXhr.status == 400) {
                    clearErrors(education);
                    var validationErrors = $.parseJSON(jqXhr.responseText);
                    $.each(validationErrors.ModelState, function (i, ival) {
                        remoteErrors(education, i, ival);
                    });
                } else {
                    $('fail-save-employee').modal('show');
                }
            }
        });

我不喜欢内联脚本,我创建了一个单独的 js 文件,我想从中进行调用。

我需要帮助

我需要帮助找出 api 控制器的正确 url,以便我可以在脚本文件中使用它。

我试过了

阅读this article我尝试了以下:

 $.post('/DefaultApi/EmployeeApi', educationAdd)

这给了我一个

404 未找到错误。

在内联脚本中,url 是这样的:

 $.post('@Url.HttpRouteUrl("DefaultApi", new { controller = "EmployeeApi", educationName = "educationCreate" })', educationAdd)

WebApiConfig.cs 文件:

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional });

我试图在 EmployeeApi 控制器中访问的方法:

 public IHttpActionResult EducationPost(EmployeeEducation model, string educationName){}

我该怎么做?

【问题讨论】:

    标签: c# jquery asp.net-web-api asp.net-mvc-5


    【解决方案1】:

    解析网址

    通常在 MVC 应用程序中,您可以通过使用 Url.Action() 帮助程序来解析正确的 URL,提供其控制器、操作和 RouteValues:

    // Supply the Action, Controller and any route values that you need
    $.post('@Url.Action("EducationPost","EmployeeApi", new { educationName = "educationCreate"})', function(){
         // Do something here
    });
    

    但是,Web API 还具有 Url.Link() 帮助器,它可能也很有用,并且以类似的方式工作,除了基于路由本身:

    $.post('@Url.Link("DefaultApi", new { controller = "EmployeeApi", action = "EductationPost", educationName = "educationCreate" })', function(){
         // Do something here
    });
    

    使用外部 Javascript 文件时

    正如您想象的那样,这些技术在使用外部 Javascript 文件时不起作用。在这些情况下,我通常建议考虑在 HTML 中使用 data-* 属性来存储 URL,然后在将触发 AJAX 调用的事件处理程序中引用它:

    <button id='call-ajax' data-post-url='@Url.Action(...)' />
    <script>
        $(function(){
              $('#call-ajax').click(function(e){
                   // Read the attribute and use it
                   $.post($(this).attr('data-post-url'), function(){
                         // All done
                   });
              });
        });
    </script>
    

    您显然可以通过使用变量或隐藏元素来实现同样的基本想法,但就实际访问它而言,同样的想法基本上适用。

    【讨论】:

    • 但是一旦我将代码放入 js 文件中,这将如何工作?我无法从那里访问剃刀语法。倾斜脚本代码位于我可以访问剃刀语法的视图中。我想将脚本移动到 js 文件并获取静态(平面)url。
    • 正确,这行不通。一般来说,我建议利用 HTML data-* 属性并使用它将目标 URL 存储在可能触发 AJAX 调用的元素上。因此,在特定的事件处理程序中,您可以使用 $(this).data('post-url') 之类的东西来解析请求中的正确 URL。这有意义吗?
    • 这可能行得通。我会试一试。请编辑您的答案,如果可行,我会接受。
    • 我添加了一个示例来展示基本思想;希望对您有所帮助。
    【解决方案2】:

    看看这个答案: How to send razor created Url to js file

    该用户提供了 3 种可能的解决方案。

    1. 全局 js 变量
    2. 自定义“data-”属性
    3. 隐藏输入

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      相关资源
      最近更新 更多