How can I make a controller in ASP.NET MVC do something(here it is inserting data in database) but doesn't load or reload the whole view just the partial view
In the view, i have got a button which will insert data into the database, and return the updated data.
I have done similar work in past, you can do same but replace your mode and it's data according to your data.
Note:
I am using Customer class data , please replace model and it's column with your data.
//Method to return Partial View
public ActionResult Table()
{
var ModelList = new List<Customer>();
using (var context = new NorthWindEntities())
{
ModelList = (from s in context.Customers
select s).ToList();
}
return PartialView(ModelList);
}
@model IEnumerable<Test.Models.Customer>
<table class="table table-condensed">
<thead>
<tr>
<th>Customer Name</th>
<th>Work Area</th>
<th>City</th>
</tr>
</thead>
<tbody>
<!--Loop through each customer to show it's data-->
@foreach (var Customer in Model)
{
<tr>
<td>@Customer.Customername</td>
<td>@Customer.WorkArea</td>
<td>@Customer.City</td>
</tr>
}
</tbody>
</table>
public ActionResult GetCustomer()
{
return View();
}
And view for it, will be
<!--Form To add new customer-->
<div class="form-group">
<div class="row">
<div class="col-lg-2">
Customer Name
</div>
<div class="col-lg-10">
@Html.TextBoxFor(a => a.Customername, new { @class = "form-control" })
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-2">
Work Area
</div>
<div class="col-lg-10">
@Html.TextBoxFor(a => a.WorkArea, new { @class = "form-control" })
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-2">
City
</div>
<div class="col-lg-10">
@Html.TextBoxFor(a => a.City, new { @class = "form-control" })
</div>
</div>
</div>
<input type="button" class="btn btn-primary" id="AddNewCustomer" value="Add New Customer" />
<!--Div to show table Data-->
<div id="TableData">
</div>
In the above view , we have added input fields to add new customer and a div to load table data in it.
Now Important step, load this script in above view, to load table using the ajax call and send new customer data using ajax
<script>
$(document).ready(function () {
//Get Table data on page load
$.ajax({
url: '/home/Table', //url to load table data
type: 'GET',
success: function (result) {
//Get result data in html and append it in the div
$("#TableData").html(result);
},
error: function () {
//Show error here
alert("Error");
}
})
//Submit Data on Click
$("#AddNewCustomer").on('click', function () {
//do validation here for data if needed.
var customers = []; //create empty array for all customer
var customer = []; //create array for customer data
//this should exactly match the columns of your table
customer = {
Customername: $("#Customername").val(),
WorkArea: $("#WorkArea").val(),
City: $("#City").val(),
ContactTitle: null,
Address:null
}
//push created customer in Customer array
customers.push(customer);
//Post data to C# controller
$.post('/Home/AddNewCustomer',
{
StringData: JSON.stringify(customers) //Send data as string data
},
function (data) {
//if there was no error, get updated data
if(data==true)
{
//Get Updated data from table
$.ajax({
url: '/home/Table', //url to load table data
type: 'GET',
success: function (result) {
//replace it with new data
$("#TableData").html(result);
},
error: function () {
//Show error here
alert("Error");
}
})
}
}
);
})
});
</script>
I have exaplined script with comments, now the last part C# code to save data in database.
[HttpPost]
public JsonResult AddNewCustomer(string StringData)
{
//Deserialize it
List<Customer> Customers = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<Customer>>(StringData);
try
{
using (var context = new NorthWindEntities())
{
//loop through customer
foreach (var Customer in Customers)
{
context.Customers.Add(Customer);
}
context.SaveChanges();
}
return Json(true);
}
catch (Exception e)
{
return Json(false);
}
}
we are posting data to controller as JSON
string and then converting it into class using JavaScriptSerializer()
That's it, we are done, you can deseriliaze a single object instead of list also.
Hopefully it will help, it was working in my project.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly