CRUD Operation in Asp.Net Core 3.1

CRUD Operation (Create, Update, Delete, Display) on single page in Asp.Net Core 3.1 Application.

October 31, 2020

In this article we will cover CRUD Operation (Create, Update, Delete, Display) on single page in Asp.Net Core 3.1 Application.

CRUD Operation is done Using jQuery Unobtrusive AJAX and Asp.Net Core API which is called using "HttpClient"

This article also contains dependent dropdown which is getting populated using jquery Ajax.

Let's Start:

Models

Create below mentioned classes inside Models folder

public class City
{
    public int City_Id { getset; }
    [Required]
    [Display(Name = "Title")]
    public string City_Title { getset; }
    [Required]
    [Display(Name = "Code")]
    public string City_Code { getset; }
    [Required]
    [Display(Name = "State")]
    public int State_Id { getset; }
    public string State_Title { getset; }
    [Required]
    [Display(Name = "Country")]
    public int Country_Id { getset; }
    public string Country_Title { getset; }
}
 
public class City_Model
{
    public City objCity { getset; }
    public IEnumerable<City> List_objCity { getset; }
    public List<SelectListItem> List_Countries = new List<SelectListItem>();
}

Controller

Create Controller named "CityController" and add below mentioned methods.

public IActionResult Index()
{
    City_Model model = new City_Model();
 
    HttpResponseMessage res = httpClient.GetAsync($"City").Result;
    if (res.IsSuccessStatusCode)
    {
        var result = res.Content.ReadAsStringAsync().Result;
        model.List_objCity = JsonConvert.DeserializeObject<IEnumerable<City>>(result);
 
        // (+) [Fill Countries]
        HttpResponseMessage resCountry = httpClient.GetAsync($"Country").Result;
        if (resCountry.IsSuccessStatusCode)
        {
            var resultCountry = resCountry.Content.ReadAsStringAsync().Result;
            var Countries = JsonConvert.DeserializeObject<IEnumerable<Country>>(resultCountry);
 
            Countries.ToList().ForEach(f =>
            {
                model.List_Countries.Add(new SelectListItem()
                {
                    Text = f.Country_Title,
                    Value = f.Country_Id.ToString()
                });
            });
        }
    }
    return View(model);
}
[HttpPost]
public async Task<IActionResultIndex(City_Model model)
{
    string msg = "error";
 
    if (model.objCity.City_Id > 0)
    {
        HttpResponseMessage res = httpClient.GetAsync($"City/{model.objCity.City_Id}").Result;
        if (res.IsSuccessStatusCode && res.StatusCode.ToString().ToLower().Equals("ok"))
        {
            var result = res.Content.ReadAsStringAsync().Result;
            var obj = JsonConvert.DeserializeObject<City>(result);
            obj.City_Title = model.objCity.City_Title.Trim();
            obj.City_Code = model.objCity.City_Code.Trim();
            obj.State_Id = model.objCity.State_Id;
            obj.Country_Id = model.objCity.Country_Id;
 
            var content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
            HttpResponseMessage res1 = httpClient.PutAsync("City"content).Result;
            if (res1.IsSuccessStatusCode)
            {
                msg = "success";
            }
        }
    }
    else
    {
        City newCity = new City();
        newCity.City_Title = model.objCity.City_Title.Trim();
        newCity.City_Code = model.objCity.City_Code.Trim();
        newCity.State_Id = model.objCity.State_Id;
        newCity.Country_Id = model.objCity.Country_Id;
 
        var content = new StringContent(JsonConvert.SerializeObject(newCity), Encoding.UTF8, "application/json");
        var resput = httpClient.PostAsync($"City"content).Result;
 
        if (resput.IsSuccessStatusCode)
            msg = "success";
    }
 
    return Ok(msg);
}
[HttpPost]
public async Task<IActionResultDelete(int id)
{
    string msg = "error";
    if (id > 0)
    {
        var res = httpClient.DeleteAsync($"City/{id}").Result;
        msg = "success";
    }
    return Ok(msg);
}
public JsonResult GetStateList(int CountryID)
{
    List<SelectListItemstatelist = new List<SelectListItem>();
    statelist.Add(new SelectListItem()
    {
        Text = "Select State",
        Value = ""
    });
    var res = httpClient.GetAsync($"State/GetByCountry/{CountryID}").Result;
    if (res.IsSuccessStatusCode)
    {
        var result = res.Content.ReadAsStringAsync().Result;
        var lstStates = JsonConvert.DeserializeObject<IEnumerable<State>>(result);
        lstStates.ToList().ForEach(f =>
        {
            statelist.Add(new SelectListItem()
            {
                Text = f.State_Title,
                Value = f.State_Id.ToString()
            });
        });
    }
    return Json(statelist);
}
 
public JsonResult GetCityList(int StateID)
{
    List<SelectListItemcitylist = new List<SelectListItem>();
    citylist.Add(new SelectListItem()
    {
        Text = "Select City",
        Value = ""
    });
 
    var res = httpClient.GetAsync($"City/GetByState/{StateID}").Result;
    if (res.IsSuccessStatusCode)
    {
        var result = res.Content.ReadAsStringAsync().Result;
        var lstCity = JsonConvert.DeserializeObject<IEnumerable<City>>(result);
        lstCity.ToList().ForEach(f =>
        {
            citylist.Add(new SelectListItem()
            {
                Text = f.City_Title,
                Value = f.City_Id.ToString()
            });
        });
    }
    return Json(citylist);
}

Views

Create "Index.cshtml" inside "City" Folder and add below mentioned html

@{
    ViewData["Title"] = "City";
    @model HpBlogs.Models.City_Model
}
<form method="post" data-ajax="true" data-ajax-method="post" data-ajax-complete="cityCallBack" data-ajax-loading="#loader-container">
    <div class="row">
        <div class="col-lg-4">
            <label>Title</label><span class="red-asterix">*</span>
            <div class="form-group">
                <input id="txtCityTitle" asp-for="objCity.City_Title" class="form-control" placeholder="City name" maxlength="100" />
                <span asp-validation-for="objCity.City_Title" class="text-danger"></span>
            </div>
        </div>
        <div class="col-lg-4">
            <label>Code</label><span class="red-asterix">*</span>
            <div class="form-group">
                <input id="txtCityCode" asp-for="objCity.City_Code" class="form-control" placeholder="City Code" maxlength="4" />
                <span asp-validation-for="objCity.City_Code" class="text-danger"></span>
            </div>
        </div>
        <div class="col-lg-4">
            <label>Country</label><span class="red-asterix">*</span>
            <div class="form-group">
                <select id="txtCountryID" asp-for="objCity.Country_Id" asp-items="Model.List_Countries" class="form-control countryDropdown">
                    <option value="">Select Country</option>
                </select>
                <span asp-validation-for="objCity.Country_Id" class="text-danger"></span>
            </div>
        </div>
        <div class="col-lg-4">
            <label>State</label><span class="red-asterix">*</span>
            <div class="form-group">
                <select id="txtStateID" asp-for="objCity.State_Id" class="form-control stateDropdown">
                    <option value="">Select State</option>
                </select>
                <span asp-validation-for="objCity.State_Id" class="text-danger"></span>
            </div>
        </div>
        <div class="col-lg-12 pb-3 py-3">
            <div class="btn-box">
                <input id="hdnCityId" type="hidden" asp-for="objCity.City_Id" />
                <button class="" id="btnAddCity">Add City</button>
                <button class=" dNone" id="btnUpdateCity">Update City</button>
                <button class=" dNone" id="btnCancelCity">Cancel</button>
            </div>
        </div>
    </div><!-- end row -->
</form>
<table>
    <thead>
        <tr>
            <th>Title</th>
            <th>Code</th>
            <th>State</th>
            <th>Country</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.List_objCity)
        {
            <tr>
                <td id="tdCityId" style="display:none">@item.City_Id</td>
                <td id="tdCountryId" style="display:none">@item.Country_Id</td>
                <td id="tdStateId" style="display:none">@item.State_Id</td>
 
                <td id="tdCityTitle">@item.City_Title</td>
                <td id="tdCityCode">@item.City_Code</td>
                <td id="tdStateTitle">@item.State_Title</td>
                <td id="tdCountryTitle">@item.Country_Title</td>
                <td>
                    <a href="#" id="EditCity">Edit</a>
                    <form asp-action="Delete" asp-route-id="@item.City_Id" data-ajax="true" data-ajax-complete="cityCallBack">
                        <button type="submit" class="" onclick="return confirm('Are you sure?')">
                            Delete
                        </button>
                    </form>
                </td>
            </tr>
        }
    </tbody>
</table>

CSS

<style>
    .dNone {
        display:none !important;
    }
</style>

Javascript

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.min.js" integrity="sha512-DedNBWPF0hLGUPNbCYfj8qjlEnNE92Fqn7xd3Sscfu7ipy7Zu33unHdugqRD3c4Vj7/yLv+slqZhMls/4Oc7Zg==" crossorigin="anonymous"></script>
<script>
    $(function () {
 
        //Bind State dropdownlist
        $(".countryDropdown").change(function () {
            $("#loader-container").show();
            var countryId = $(this).val();
            var $this = $(this);
            $.getJSON("/city/GetStateList", { CountryId: countryId }, function (data) {
                var item = "";
                $(".stateDropdown").empty();
                $.each(data, function (icity) {
                    item += '<option value="' + city.value + '">' + city.text + '</option>'
                });
                $(".stateDropdown").html(item);
 
                if (typeof $this.attr("stateid") !== 'undefined') {
                    $("#txtStateID").val($this.attr("stateid"));
                    $this.removeAttr("stateid");
                }
 
                if (typeof $this.attr("cityid") !== 'undefined') {
                    $(".stateDropdown").attr("cityid", $this.attr("cityid"));
                    $(".stateDropdown").trigger("change");
                }
                $("#loader-container").hide();
            });
        });
        //Bind City dropdownlist
        $(".stateDropdown").change(function () {
            if ($(".cityDropdown").length > 0) {
                var $this = $(this);
                $("#loader-container").show();
                var stateId = $(this).val();
                $.getJSON("/city/GetCityList", { StateId: stateId }, function (data) {
                    var item = "";
                    $(".cityDropdown").empty();
                    $.each(data, function (icity) {
                        item += '<option value="' + city.value + '">' + city.text + '</option>'
                    });
                    $(".cityDropdown").html(item);
 
                    if (typeof $this.attr("cityid") !== 'undefined') {
                        $("#txtCityID").val($this.attr("cityid"));
                        $this.removeAttr("cityid");
                        $(".countryDropdown").removeAttr("cityid");
                    }
                    $("#loader-container").hide();
                });
            }
        });
 
        $(document).on("click""#EditCity"function (e) {
            e.preventDefault();
 
            $("#btnAddCity").addClass("dNone");
            $("#btnUpdateCity").removeClass("dNone");
            $("#btnCancelCity").removeClass("dNone");
 
            var CloseTr = $(this).closest("tr");
 
            $("#txtCityTitle").val(CloseTr.find("td#tdCityTitle").text());
            $("#txtCityCode").val(CloseTr.find("td#tdCityCode").text());
            $("#txtCountryID").val(CloseTr.find("td#tdCountryId").text());
            $("#hdnCityId").val(CloseTr.find("td#tdCityId").text());
            $(".countryDropdown").attr("stateid", CloseTr.find("td#tdStateId").text());
            $(".countryDropdown").trigger("change");
        });
 
        $(document).on("click""#btnCancelCity"function (e) {
            e.preventDefault();
            $("#btnAddCity").removeClass("dNone");
            $("#btnUpdateCity").addClass("dNone");
            $("#btnCancelCity").addClass("dNone");
 
            $("#txtCityTitle").val("");
            $("#txtCityCode").val("");
            $("#txtStateID").val("");
            $("#txtCountryID").val("");
            $("#hdnCityId").val("0");
            $(".stateDropdown").find('option').not(':first').remove();
        });
 
    });
 
    cityCallBack = (e) => {
        console.log(e);
        if (e.responseText === "success")
            window.location.reload();
        else
            alert(e.responseText);
    };
 
</script>

Note: In this article i have used API for CRUD Operation. You can do this using any method. (Call API or Store Data Directly in Database without API)

Post Comments(2)

AntoniotaidsDecember 21, 2021

It completely agree with told all above. https://blackdogname.com/wp-content/popul/

AntoniotaidsDecember 31, 2021

But before moving to the practical demonstration of CRUD operation in Asp.Net Core Web API. Let understand the objective of this demonstration which tells what exactly will be covered in this article.

Leave a reply

Will not be displayed in comment box .

Loading...