1

I inherited some code and I am trying to figure the right url to a webapi controller but my knowledge of mvc web api is lacking.

I have inline script that is making an ajax post like this:

$('#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');
                }
            }
        });

I don't like inline script and I have created a seperate js file where I want to make this call from.

I need help with

I need help figuring out the right url to the api controller so that i can use it in the script file.

I tried

Reading this article I tried the following:

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

This gave me a

404 not found error.

in the inline script the url is like this:

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

WebApiConfig.cs file:

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

method I am trying to access in EmployeeApi controller:

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

How can I do this?

ThunD3eR
  • 3,216
  • 5
  • 50
  • 94

2 Answers2

1

Resolving the URL

Generally in MVC applications, you would resolve this by using the Url.Action() helper to resolve the proper URL provided its Controller, Action and RouteValues:

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

However, Web API also features the Url.Link() helper that might be useful as well and works in a similar manner except based on the route itself :

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

When using External Javascript Files

As you would imagine, these techniques won't work when using external Javascript files. What I generally recommend in these situations is to consider using a data-* attribute in HTML to store the URL and then reference that within your event handler that will trigger the AJAX call :

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

You could obviously accomplish this same basic idea through the use of variables or hidden elements, but the same idea basically holds true as far as actually accessing it goes.

Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • But how will this work once i put the code in a js file? I can't access the razor syntax from there. The incline script code is inside of a view where i have access to the razor syntax. I want to move the script to a js file and get the static (plane) url. – ThunD3eR May 18 '16 at 14:45
  • Correct, this won't work. Generally what I recommend is to take advantage of HTML `data-*` attributes and use that to store the target URL on the element that might be triggering the AJAX call. So in a specific event handler, you could use something like `$(this).data('post-url')` to resolve the proper URL within your request. Does that make sense? – Rion Williams May 18 '16 at 14:48
  • That might work. I'll give it a try. Please edit you answer and if it works i will accept it. – ThunD3eR May 18 '16 at 14:50
  • I've added an example demonstrating the basic idea; Hope it helps. – Rion Williams May 18 '16 at 14:52
1

Have a look at this answer: How to send razor created Url to js file

This user offers 3 possible solutions.

  1. global js variable
  2. custom "data-" attribute
  3. hidden input
Petre Ionescu
  • 174
  • 1
  • 8