Junaid
Junaid

Reputation: 1030

Cannot hit WebAPI method from ajax but can hit it from postman in asp.net

Action

// POST: api/UserAPIJson
[HttpPost]
public void Post(User user)
{
    if (ModelState.IsValid)
    {
        string json = JsonConvert.SerializeObject(user);
        //write string to file
        System.IO.File.WriteAllText(@"G:\path.json", json);
    }
}

HTML Markup

<div class="form-horizontal">
        <h4>User</h4>
        <hr />
        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" id="btnCreate" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>

SCRIPT

<script>

        $(document).ready(function () {
            var userObj = null;
            $('#btnCreate').click(function (e) {
                e.preventDefault();

                var fName = $('#FirstName').val();
                var lName = $('#LastName').val();

                if (fName != "" || lName != "") {
                    userObj = { FirstName: fName, LastName: lName };
                }

                if (userObj != null) {
                    debugger;
                    $.ajax({
                        type: "POST",
                        URL: "/api/UserAPIJson",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify(userObj),
                        success: function (response) {
                            alert("Inserted!");
                        },
                        error: function (response) {
                            alert("Error:" + response);
                        }
                    });
                }
                else {
                    alert("Please enter valid data!");
                }
            });
        });
    </script>

The same request is hitting from Postman and 204 is returned as my action returns void.

Postman: enter image description here

WebApiConfig

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

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

Global.asax

 void Application_Start(object sender, EventArgs e)
            {
                // Code that runs on application startup
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                RouteConfig.RegisterRoutes(RouteTable.Routes);            
            }

Problem: I have a simple controller and then an API controller. The page always posts back to Index method of the simple controller rather than API controller. I have no form tags in the markup.

Upvotes: 0

Views: 325

Answers (1)

Remay
Remay

Reputation: 69

url must be in lower case => url: "/api/UserAPIJson" .You don't need to name your data

Upvotes: 1

Related Questions