如何将url.HttpRouteUrl转换为普通的字符串url?

时间:2016-05-18 14:32:20

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

我继承了一些代码,我试图找到一个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){}

我该怎么做?

2 个答案:

答案 0 :(得分:1)

解析网址

通常在MVC应用程序中,您可以使用Url.Action()帮助程序解决此问题,以解析其Controller,Action和RouteValues提供的正确URL:

// 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>

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

答案 1 :(得分:1)

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

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

  1. 全球js变量
  2. 自定义“data-”属性
  3. 隐藏输入
相关问题