1

I have written simple webapi method. I am trying to access that method in mvc using ajax call. I am getting output in browser and fiddler . But Its not working in cshtml page.Please let me know , If I have to add something. Please look into this..

 function validate() {
            alert("came");
            $.ajax({
                url: 'http://localhost:54544/api/home/getname/',
                method: 'GET',
                contentType: 'application/form-url-encoded',
                
                success: function ()
                {
                    alert("success");
                },
                error: function (ex) {
                    alert(ex.responseText);
                }
            });

        }

Please check this images

check the html code here

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>View</title>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script type="text/javascript">
        // beforeSend: function(xhr, settings) { xhr.setRequestBody('Authorization','Bearer ' + token); } ,

        $(document).ready(function () {

            alert("came");

            $.ajax({
                url: "http://localhost:54544/api/home/getname/",
                type: "Get",
                success: function (data) {

                    alert("test came");

                },
                error: function (msg) { alert("error"); alert(msg); }
            });
        });

    </script>


</head>
<body>
    <div>

        <table>
            <tbody>
                <tr>
                    <td><input type="button" value="Submit" onclick="validate()" name="Submit" /> </td>
                </tr>
            </tbody>


        </table>

    </div>
</body>
</html>

how to add request body parameters in ajax request

3
  • I tried removing content type., but Its not working. Commented Nov 7, 2015 at 6:38
  • Any error on your browser console? Post your complete cshtml and Layout page, did you wrap it in section? Because by the default template, if you call <script></script> immediately in your cshtml without wrapping it in section, it will be called before the jquery.js and will cause error because the jquery.js is being called after RenderBody() in the Layout page Commented Nov 7, 2015 at 8:33
  • added cshtml. Please check once and error in console : XMLHttpRequest cannot load localhost:54544/api/home/getname. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:57842' is therefore not allowed access. Commented Nov 7, 2015 at 11:34

1 Answer 1

1

It looks like you are violating the same origin policy restriction by trying to make an AJAX call to another domain. For this to work you might need to enable CORS in your Web API. If you are using ASP.NET Web API you may checkout the following tutorial which illustrates how this can be done.

Basically you can install the Microsoft.AspNet.WebApi.Cors NuGet:

Install-Package Microsoft.AspNet.WebApi.Cors

and enable CORS in your bootstrapper:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();
        ...
    }
}

Finally decorate your API controller with the [EnableCors] attribute:

[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
public class ItemsController : ApiController
{
    public HttpResponseMessage Get() { ... }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply. i got this. and one more doubt, I have attached one image link Please let me know how to add req body parameters in ajax call
You seem to have passed a wrong content type header in your request: application/form-url-encoded. The correct content type is application/x-www-form-urlencoded, so make sure that you respect the standard encoding headers when making your HTTP request in Fiddler.

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.