Hi rani,
Refer below example.
For reading connection string refer below article.
Database
I have made use of table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
Namespaces
using System.Data;
using System.Data.SqlClient;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc.Rendering;
Model
using System.ComponentModel.DataAnnotations;
namespace CRUD_Modal_Partial_Core_MVC.Models
{
public class Customer
{
public int Id { set; get; }
[Required(ErrorMessage = "Name Required!")]
public string Name { set; get; }
[Required(ErrorMessage ="Country Required!")]
public string Country { set; get; }
}
}
Controller
public class HomeController : Controller
{
private IConfiguration Configuration;
public HomeController(IConfiguration _configuration)
{
Configuration = _configuration;
}
private string GetConnectionString()
{
return this.Configuration.GetConnectionString("MyConn");
}
public IActionResult Index()
{
ViewBag.Name = "Add";
ViewBag.Countries = PopulateCountries();
Customer customer = new Customer();
customer.Customers = GetCustomers(null);
return View(customer);
}
public IActionResult Create(Customer customer)
{
ViewBag.Countries = PopulateCountries();
AddUpdateDeleteCustomer(customer, "Insert");
return RedirectToAction("Index");
}
public IActionResult Update(Customer customer)
{
ViewBag.Countries = PopulateCountries();
ViewBag.Name = "Add";
AddUpdateDeleteCustomer(customer, "Update");
return RedirectToAction("Index");
}
public IActionResult Delete(int id)
{
ViewBag.Countries = PopulateCountries();
ViewBag.Name = "Add";
AddUpdateDeleteCustomer(new Customer { Id = id }, "Delete");
return RedirectToAction("Index");
}
[HttpPost]
public IActionResult AddCustomer()
{
ViewBag.Countries = PopulateCountries();
ViewBag.Name = "Add";
Customer customer = new Customer();
return PartialView("_InsertUpdatePartial", customer);
}
[HttpPost]
public IActionResult EditCustomer([FromBody]Customer cust)
{
ViewBag.Countries = PopulateCountries();
int id = Convert.ToInt32(cust.Id);
ViewBag.Name = "Update";
Customer customer = new Customer();
customer.Id = id;
customer.Name = GetCustomers(id).FirstOrDefault().Name;
customer.Country = GetCustomers(id).FirstOrDefault().Country;
customer.Customers = GetCustomers(null);
return PartialView("_InsertUpdatePartial", customer);
}
public List<Customer> GetCustomers(int? id)
{
List<Customer> customers = new List<Customer>();
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clear();
if (id != null)
{
cmd.CommandText = "SELECT * FROM Customers WHERE CustomerId = @Id";
cmd.Parameters.AddWithValue("@Id", id);
}
else
{
cmd.CommandText = "SELECT * FROM Customers";
}
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
customers.Add(new Customer()
{
Id = Convert.ToInt32(rdr["CustomerId"]),
Name = rdr["Name"].ToString(),
Country = rdr["Country"].ToString()
});
}
con.Close();
}
}
return customers;
}
public void AddUpdateDeleteCustomer(Customer customer, string action)
{
if (PopulateCountries().Find(x => x.Value == customer.Country) != null)
{
customer.Country = PopulateCountries().Find(x => x.Value == customer.Country).Text;
}
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.Clear();
if (action == "Insert")
{
cmd.CommandText = "INSERT INTO Customers VALUES (@Name,@Country)";
cmd.Parameters.AddWithValue("@Name", customer.Name);
cmd.Parameters.AddWithValue("@Country", customer.Country);
}
else if (action == "Update")
{
cmd.CommandText = "UPDATE Customers SET NAME = @Name,Country = @Country WHERE CustomerId = @Id";
cmd.Parameters.AddWithValue("@Id", customer.Id);
cmd.Parameters.AddWithValue("@Name", customer.Name);
cmd.Parameters.AddWithValue("@Country", customer.Country);
}
else if (action == "Delete")
{
cmd.CommandText = "DELETE FROM Customers WHERE CustomerId = @Id";
cmd.Parameters.AddWithValue("@Id", customer.Id);
}
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
private List<SelectListItem> PopulateCountries()
{
List<SelectListItem> countries = new List<SelectListItem>();
countries.Add(new SelectListItem { Text = "Select", Value = "" });
countries.Add(new SelectListItem { Text = "USA", Value = "1" });
countries.Add(new SelectListItem { Text = "India", Value = "2" });
countries.Add(new SelectListItem { Text = "Russia", Value = "3" });
countries.Add(new SelectListItem { Text = "France", Value = "4" });
return countries;
}
}
View
Index
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model CRUD_Modal_DropDown_Core_MVC.Models.Customer
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script type="text/javascript">
$(function () {
$("body").on('click', '#btnEdit', function () {
$("#MyPopup").modal("hide");
var obj = {};
obj.Id = $(this).attr('data-id');
$.ajax({
url: 'Home/EditCustomer',
data: JSON.stringify(obj),
type: 'POST',
dataType: 'html',
contentType: "application/json; charset=utf-8",
success: function (response) {
$("#dvPartial").html(response);
$("#MyPopup").modal("show");
$("#ddlCountries option:contains(" + $(response).find('#hfCountry').val() + ")").attr('selected', 'selected');
}
});
});
$("body").on('click', '#btnAdd', function () {
$.ajax({
url: 'Home/AddCustomer',
data: {},
type: 'POST',
dataType: 'html',
contentType: "application/json; charset=utf-8",
success: function (response) {
$("#dvPartial").html(response);
$("#MyPopup").modal("show");
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h4>Customers</h4>
<table class="table table-responsive">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.Name)</th>
<th>@Html.DisplayNameFor(model => model.Country)</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var customer in Model.Customers)
{
<tr>
<td>@Html.DisplayFor(x => customer.Name)</td>
<td>@Html.DisplayFor(x => customer.Country)</td>
<td>
<a href="#" id="btnEdit" class="btn btn-primary btn-sm" data-id="@customer.Id">Edit</a>
</td>
<td>@Html.ActionLink("Delete", "Delete", new { id = customer.Id }, new { onclick = "return confirm('Are you sure you wish to delete this Customer?');", @class = "btn btn-danger btn-sm" })</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<p>
<a id="btnAdd" class="btn btn-outline-success btn-sm">Add Customer</a>
</p>
</div>
<!-- Modal Popup -->
<div id="MyPopup" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<div id="dvPartial"></div>
</div>
<div class="modal-footer">
<input type="button" id="btnClosePopup" value="Close" data-dismiss="modal" class="btn btn-danger" />
</div>
</div>
</div>
</div>
</body>
</html>
PartialView
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model CRUD_Modal_DropDown_Core_MVC.Models.Customer
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script type="text/javascript">
$(function () {
$("body").on('change', '#ddlCountries', function () {
$('#hfCountry').val($(this).find('option:selected').text());
});
$("body").on('click', '#btnCreate', function () {
if (!$('form').valid()) {
$("#MyPopup").modal("show");
return false;
}
});
});
</script>
<div class="container">
<h4>Add/Update Customer</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create" asp-controller="Home">
@if (ViewBag.Name != "Add")
{
<div class="form-group">
<label asp-for="Id" class="control-label"></label>
<input asp-for="Id" class="form-control" readonly="readonly" />
</div>
}
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="hidden" id="hfCountry" asp-for="Country" />
<label asp-for="Country" class="control-label"></label>
<select name="Country" asp-items="@ViewBag.Countries" id="ddlCountries" class="form-control"></select>
<span asp-validation-for="Country" class="text-danger"></span>
</div>
<div class="form-group">
@if (ViewBag.Name == "Add")
{
<input id="btnCreate" type="submit" value="Add" asp-action="Create" class="btn btn-success btn-sm" />
}
else
{
<input type="submit" value="Update" asp-action="Update" class="btn btn-success btn-sm" />
<input type="submit" value="Cancel" asp-action="Index" class="btn btn-defaul btn-sm" />
}
</div>
</form>
</div>
</div>
</div>
Screenshot