1

I am facing problem to call user defined web api function in MVC4 Please suggest how can i do this. i am first time using web api.

My API Function :

     public List<Voice> GetVoicesByStatus(string Status)
    {
        List<Voice> Voc = db.Voices.Where(x => x.Status == Status).ToList();
        if (Status == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }

        return Voc;
    }

Ajax Method :

       function GetVoicesByStatus(status) {
        $.ajax({
            type: 'GET',
            url: 'http://xx.xx.xx.xx.xx:xx/api/Applications/VoicesByStatus/' + status,
            data: JSON.stringify({}),
            contentType: 'application/json',
            dataType: 'json',
            headers: { 'AuthToken': '2FEA7374-EBA2-4367-9492-6DB3334AD2AF' },
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var str = "<tr><td>" + data[i].ID + "</td><td>" + data[i].APIKey + "</td><td>" + data[i].CreatedBy + "</td><td><a href='#' onclick='fnDelete(&#39;" + data[i].ID + "&#39;)'>Delete</a></td></tr>";
                    $("#app").append(str);
                }

            }
        });
    }

Error :

enter image description here

2
  • Seems it's a CORS issue. You try to call a different address than your own application? Commented Mar 11, 2015 at 12:27
  • It is working with other HTTP Verb like GET, PUT, POST and DELETE but when i am calling my own function is showing error and by the way how can i call it in ajax method Commented Mar 11, 2015 at 12:35

2 Answers 2

1

Try with following code

$.ajax({
            type: 'GET',
            url: 'http://xx.xx.xx.xx.xx:xx/api/Applications/GetVoicesByStatus?status=' + status,
            contentType: 'application/json',T                
            headers: { 'AuthToken': '2FEA7374-EBA2-4367-9492-6DB3334AD2AF' },
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var str = "<tr><td>" + data[i].ID + "</td><td>" + data[i].APIKey + "</td><td>" + data[i].CreatedBy + "</td><td><a href='#' onclick='fnDelete(&#39;" + data[i].ID + "&#39;)'>Delete</a></td></tr>";
                    $("#app").append(str);
                }

            }
Sign up to request clarification or add additional context in comments.

Comments

0

I think it is CORS related issue. In MVC4 there is no default CORS handler. And use JSONP for as data-type. For enabling CORS please refer below link.

http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx

It may helps you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.