Insert record using Web API in ASP.NET MVC

How to insert a record into database by consuming ASP.NET Web API from ASP.NET MVC View?

To insert a record into the database by consuming ASP.NET Web API from ASP.NET MVC view, we can follow below approach.

Create a view with the respective fields.


    ViewBag.Title = "Create";
        <label>First Name</label>
        <label>Last Name</label>
        @Html.DropDownList("Active", new List<selectlistitem>
new SelectListItem {Text = "Yes", Value = "true", Selected = true},
new SelectListItem {Text = "No", Value = "false"},
}, "Select ...")
        <button id="btnAdd">Add</button>
        @Html.ActionLink("Back to List", "ListRecords")

    <script type="text/javascript">

        $("#btnAdd").click(function () {

            var PersonalDetails = {
                "FirstName": $("#FirstName").val(),
                "LastName": $("#LastName").val(),
                "Age": $("#Age").val(),
                "Active": $("#Active").val()

                type: "POST",
                url: 'http://localhost:28206/api/PersonalDetails/PostPersonalDetails',
                data: JSON.stringify(PersonalDetails),
                contentType: "application/json;charset=utf-8",
                success: function (data, status, xhr) {
                    alert("The result is : " + status + ": " + data);
                error: function (xhr) {

In the above code, we have three TextBoxes for FirstName, LastName, Age field of the database table and then a dropdown for the Active field.

Notice the JavaScript code block now. When the Add button is clicked we are forming a JavaScript object and setting respective property of the Model with the value of the TextBox and the DropDown. Next we are calling jQuery Ajax method to post the data on the web api url.

In the jQuery.Ajax method, we are setting following properties

  1. type : “POST”
  2. url : the url of the Web API that is responsible to accept the Model object and insert the data
  3. data: the JavaScript object is being stringify so that it can be posted to the server
  4. contentType : setting the type of content being sent from this page
  5. success: function that is giving the alert once the data is processed on the server successfully
  6. error: function that shows the response error text in case error occurred on the server


        public IHttpActionResult PostPersonalDetails([FromBody] PersonalDetails
            if (!ModelState.IsValid)
                return BadRequest(ModelState);


            return Ok(personaldetails);

In the controller action method, notice that the return type of IHttpActionResult. The JavaScript object that is sent via API gets converted into the PersonalDetails object as the name of the JavaScript object properties and the Model object properties are same.

In this method, we are checking for ModelState validity, if not valid, BadRequest is being returned otherwise data is being added into the database and Ok(with the PersonalDetails) object is being returned that show success message to the browser.

 Views: 6727 | Post Order: 122

Write for us