Friday, August 29, 2014

CRUD Operation using Asp.Net Mvc Web Api and Entity Framework in Asp.Net Mvc 4

CRUD Operation using Asp.Net Mvc Web Api and Entity Framework in Asp.Net Mvc 4

In this article, I’m explaining how to create asp.net mvc web api and how to perform CRUD (Create, Read, Update, Delete) Operations using asp.net mvc web api and entity framework in asp.net mvc 4.


If you want to learn the entity framework first, then you can read my blog here:


Example

In this example, we will create asp.net mvc web api with create, read, update and delete operations and will implement these operations in a controller using entity framework.


Step 1

First create a table in the database named “Product” like this:




And add some dummy data in it:



Step 2

Now create a basic asp.net mvc 4 application and add a class named “Product” to it:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace AspNetWebApiAndEntityFramework.Models
{
    [Table("Product")]
    public class Product
    {
        [Key]
        public int ProductId { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public string Price { get; set; }
    }
}





Step 2

Now add another class named “ProductEntities” like this:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace AspNetWebApiAndEntityFramework.Models
{
    public class ProductEntities : DbContext
    {
        public DbSet<Product> Products { get; set; }
    }
}




Step 3

Now add a controller named “ValuesController” to the project and change its base class from Controller to ApiController like this:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using AspNetWebApiAndEntityFramework.Models;

namespace AspNetWebApiAndEntityFramework.Controllers
{
    public class ValuesController : ApiController
    {
        ProductEntities db = new ProductEntities();

        public IEnumerable<Product> Get()
        {
            return db.Products.ToList();
        }

        public Product Get(int id)
        {
            return db.Products.Find(id);
        }

        public void Post(List<string> val)
        {
            Product product = new Product();
            product.Name = val[0];
            product.Category = val[1];
            product.Price = val[2];

            db.Products.Add(product);
            db.SaveChanges();
        }

        public void Put(int id, Product product)
        {
            db.Entry(product).State = System.Data.EntityState.Modified;
            db.SaveChanges();
        }


        public void Put(List<string> val)
        {
            int id = Convert.ToInt32(val[3]);
            Product product = db.Products.Find(id);
            product.Name = val[0];
            product.Category = val[1];
            product.Price = val[2];
            db.Products.Add(product);
            db.Entry(product).State = System.Data.EntityState.Modified;
            db.SaveChanges();
        }


        public void Delete(int id)
        {
            Product product = db.Products.Find(id);
            db.Products.Remove(product);
            db.SaveChanges();
        }
    }
}





Step 4

Now add another controller named “HomeController” like this:





And write the below code in it:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AspNetWebApiAndEntityFramework.Models;

namespace AspNetWebApiAndEntityFramework.Controllers
{
    public class HomeController : Controller
    {
        ValuesController db = new ValuesController();
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View(db.Get());
        }

        //
        // GET: /Home/Details/5

        public ActionResult Details(int id = 0)
        {
            Product product = db.Get(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        //
        // GET: /Home/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Home/Create

        [HttpPost]
        public ActionResult Create(Product product)
        {
            if (ModelState.IsValid)
            {
                List<string> productList = new List<string>();
                productList.Add(product.Name);
                productList.Add(product.Category);
                productList.Add(product.Price);
                db.Post(productList);
                return RedirectToAction("Index");
            }

            return View(product);
        }

        //
        // GET: /Home/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Product product = db.Get(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        //
        // POST: /Home/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, Product product)
        {

            if (ModelState.IsValid)
            {
                db.Put(id, product);
                return RedirectToAction("Index");
            }
            return View(product);
        }

        //
        // GET: /Home/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Product product = db.Get(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        //
        // POST: /Home/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            db.Delete(id);
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}




Step 5

Now add the connection string in the web.config file lie this:
<connectionStrings>
  <add name="ProductEntities" connectionString="Data Source=DELL-PC\SQLEXPRESS;Initial Catalog=sumit_db;Integrated Security=true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>




Now your solution explorer will look like this:




Output

Now run the application




Click on edit:







Click on details:




Click on create new:






Click on delete:




Posted By +Sumit Kesarwani 


Monday, August 25, 2014

Cascading Dropdownlist using Ajax in Asp.Net Mvc 4

Cascading Dropdownlist using Ajax in Asp.Net Mvc 4

In this blog, I’m explaining how to create cascading dropdownlist using ajax in asp.net mvc 4.

Cascading dropdownlist means there will be two or more than two dropdownlist in a single webpage and one dropdownlist will be based on other dropdownlist means once we select value in one dropdownlist, it will filter the value in the second dropdownlist.



Example

In this example, we will have three dropdownlist – Country, State, City. Once we select the value in Country dropdownlist – it will filter the value in State dropdownlist and once we select the value in the State dropdownlist – it will filter the value in the City dropdownlist and all these task will going to achieve using ajax because we don’t want to reload the page each and every time the user selects the value in any of the dropdownlist.



Step 1

First create three tables in the database like this:

Country




State




City





Step 2

Now create a basic asp.net mvc 4 application and add three model class like this:

CountryModel

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace CascadingDropDownListMvcApp.Models
{
    [Table("Country")]
    public class CountryModel
    {
        [Key]
        public int CountryId { get; set; }
        public string Country { get; set; }
    }
}




StateModel

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace CascadingDropDownListMvcApp.Models
{
    [Table("State")]
    public class StateModel
    {
        [Key]
        public int Id { get; set; }
        public int CountryId { get; set; }
        public string State { get; set; }
    }
}




CityModel

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace CascadingDropDownListMvcApp.Models
{
    [Table("City")]
    public class CityModel
    {
        [Key]
        public int Id { get; set; }
        public int StateId { get; set; }
        public string City { get; set; }
    }
}



Step 3

Now add another class to the project named “CountryEntities” like this:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace CascadingDropDownListMvcApp.Models
{
    public class CountryEntities : DbContext
    {
        public DbSet<CountryModel> Countries { get; set; }
        public DbSet<StateModel> States { get; set; }
        public DbSet<CityModel> Cities { get; set; }
    }
}



Step 4

Now add a controller to the project named “HomeController” and write the below code in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CascadingDropDownListMvcApp.Models;

namespace CascadingDropDownListMvcApp.Controllers
{
    public class HomeController : Controller
    {
        CountryEntities db = new CountryEntities();

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetCountries()
        {
            return Json(db.Countries.ToList(), JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetStatesByCountryId(string countryId)
        {
            int Id = Convert.ToInt32(countryId);
            var states = from a in db.States where a.CountryId == Id select a;
            return Json(states);
        }

        public JsonResult GetCitiesByStateId(string stateId)
        {
            int Id = Convert.ToInt32(stateId);
            var cities = from a in db.Cities where a.StateId == Id select a;
            return Json(cities);
        }
    }
}



Step 5

Now add a view to the project named “Index” and write the below code in it:
@{
    ViewBag.Title = "Index";
}

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script>
    $(function () {
        $.ajax({
            type: "GET",
            url: "/home/GetCountries",
            datatype: "Json",
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#dropdownCountry').append('<option value="' + value.CountryId + '">' + value.Country + '</option>');
                });
            }
        });

        $('#dropdownCountry').change(function () {

            $('#dropdownState').empty();

            $.ajax({
                type: "POST",
                url: "/home/GetStatesByCountryId",
                datatype: "Json",
                data: { countryId: $('#dropdownCountry').val() },
                success: function (data) {
                    $.each(data, function (index, value) {
                        $('#dropdownState').append('<option value="' + value.Id + '">' + value.State + '</option>');
                    });
                }
            });
        });

        $('#dropdownState').change(function () {

            $('#dropdownCity').empty();

            $.ajax({
                type: "POST",
                url: "/home/GetCitiesByStateId",
                datatype: "Json",
                data: { stateId: $('#dropdownState').val() },
                success: function (data) {
                    $.each(data, function (index, value) {
                        $('#dropdownCity').append('<option value="' + value.Id + '">' + value.City + '</option>');
                    });
                }

            });
        });

    });
</script>


<h2>Cascading DropDownList Sample</h2>
<div>
    <div style="width: 100%;float:left;">
        <div style="width: 100px; float: left;">
            <label>Country : </label>
        </div>
        <div style="width: 200px; float: left;">
            @Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please select country", new { @style = "width:200px;" })
        </div>
    </div>
    <div style="width: 100%;float:left;margin-top:35px;">
        <div style="width: 100px; float: left;">
            <label>State : </label>
        </div>
        <div style="width: 200px; float: left;">
            @Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please select state", new { @style = "width:200px;" })
        </div>
    </div>
    <div style="width: 100%;float:left;margin-top:35px;">
        <div style="width: 100px; float: left;">
            <label>City : </label>
        </div>
        <div style="width: 200px; float: left;">
            @Html.DropDownList("dropdownCity", new SelectList(string.Empty, "Value", "Text"), "Please select city", new { @style = "width:200px;" })
        </div>
    </div>
</div>



Step 6

Now add the connection string in the web.config file like this:
<connectionStrings>
      <add name="CountryEntities" connectionString="Data Source=DELL-PC\SQLEXPRESS;Initial Catalog=sumit_db;Integrated Security=true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>



Now your solution explorer looks like this:




Output

Now run the application













Thank you for reading this blog please put your valuable comment or any suggestion/question in the comment box.