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.
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
Hope this article will be helpful for someone.
Thanks for reading and do refer this article to your friend and colleagues.