Inserting record into database using ASP.NET MVC with Web API

Sheonarayan
Posted by in jQuery category on for Advance level | Points: 250 | Views : 63314 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article, we are going to learn how to insert a record into the database using ASP.NET MVC with Web API.

Introduction

ASP.NET Web API (Application Programming Interface) is a framework for building Web APIs on top of the .NET Framework. In this article, we shall learn how to insert a record into database using ASP.NET MVC with Web API.


Assumptions


Here following assumptions are made
  1. Reader has good knowledge of jQuery and jQuery javascript file has been referenced on the page
  2. Reader has good knowledge of ASP.NET MVC

Using the code


My ASP.NET MVC model structure looks like below assuming the database table name is "PersonalDetails".

public class PersonalDetails
    {
        [Key]
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        public int AutoId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public bool Active { get; set; }
    }
Based on above mode, we have created a view ASP.NET MVC view and below is the code for that. In this we have created three textboxes, one dropdown and a button.
<h2>Create</h2>
<div>
    <label>First Name</label>
    @Html.TextBox("FirstName")
</div>
<div>
    <label>Last Name</label>
    @Html.TextBox("LastName")
</div>
<div>
    <label>Age</label>
    @Html.TextBox("Age")
</div>
<div>
    <label>Active</label>
    @Html.DropDownList("Active", new List<SelectListItem>
    {
        new SelectListItem {Text = "Yes", Value = "true", Selected = true},
        new SelectListItem {Text = "No", Value = "false"},
    }, "Select ...")
</div>
<div>
    <button id="btnAdd">Add</button> 
    @Html.ActionLink("Back to List", "ListRecords")
</div>
Clicking on the button fires up a JavaScript function and below is the code for that.

<script type="text/javascript">

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

        var PersonalDetails = {
            "FirstName": $("#FirstName").val(),
            "LastName": $("#LastName").val(),
            "Age": $("#Age").val(),
            "Active": $("#Active").val()
        };
        
        $.ajax({
            type: "POST",
            url: 'http://localhost:28206/api/PersonalDetails/PostPersonalDetails',
            data: JSON.stringify(PersonalDetails),
            contentType: "application/json;charset=utf-8",
            processData: true,
            success: function (data, status, xhr) {
                alert("The result is : " + status);
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });
    });
</script>
In the above function, we are first creating a prototype (like a class object) of JavaScript and setting its properties values matching with the ASP.NET MVC model.

Then we are using $.ajax post method to submit the data on the API controller. Here is the code for the ASP.NET MVC API Controller. Please note that it is not normal ASP.NET MVC Controller but ApiController.

 public class PersonalDetailsController : ApiController
    {
        private MVCWebAPIContext db = new MVCWebAPIContext();
        
        [HttpPost]
        public IHttpActionResult PostPersonalDetails([FromBody] PersonalDetails personaldetails)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.PersonalDetails.Add(personaldetails);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = personaldetails.AutoId }, personaldetails);
        }
}
When the Add button is clicked, ajax request goes to above PostPersonalDetails action method and the JavaScript prototype PersonalDetails object is converted to the ASP.NET MVC PersonalDetails model and record has been inserted into the database using Entity Framework.

After a record is inserted, user gets an alert box with success message otherwise $.ajax error function fires and gives error response.

Important

Please note that $.ajax POST method doesn't work in the latest version of Internet Explorer (IE) browser. To make this work in IE, please visit Solution - jQuery post doesn't work in Internet Explorer (IE) post.

Hope this article will be helpful for someone. 

Thanks for reading and do refer this article to your friend and colleagues.

Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)