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.
VIEW CODE
@{ ViewBag.Title = "Create"; } <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> <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", success: function (data, status, xhr) { alert("The result is : " + status + ": " + data); }, error: function (xhr) { alert(xhr.responseText); } }); }); </script>
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
WEB API CONTROLLER METHOD
[HttpPost] public IHttpActionResult PostPersonalDetails([FromBody] PersonalDetails personaldetails) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.PersonalDetails.Add(personaldetails); db.SaveChanges(); 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.