March 2016 ~ MiTechDev.com

Thursday, 31 March 2016

CRUD operations in ASP.NET MVC using Jquery,EF Part 2

10:00:00 Posted by raviteja swayampu , , 1 comment
Introduction:
This article is continuation for the previous article please refer previous article before going through this article.
In part 1 of the article we had created a Controller with action methods and index view of the application. now in this article we are going to create all other pages(partial views create,edit,delete,details).
Step 1: Create partial views
1.Right click on Views folder-->  Add-->View.
2.In Add window popup name the partial view as create-->check the 'Create Partial view ' checkbox.



3.Create partial created now replace the code with below code.

Create.cshtml:
@model WvcCrudusingJqueryUI.Models.User
@{
    Layout = null;
}
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ContactNo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ContactNo)
            @Html.ValidationMessageFor(model => model.ContactNo)
        </div>
        <p>
            <input type="submit" id="btnsubmit" value="Create" />&nbsp;&nbsp;
            <input type="button" value="cancel" id="btncancel" />
        </p>
    </fieldset>
}

Step 2:
1.Similarly create all the other partial views for details,update with following code..
details.cshtml:
@model WvcCrudusingJqueryUI.Models.User
<fieldset>
    <legend>User</legend>
    <div class="display-label" style="font-size:20px;">
         @Html.DisplayNameFor(model => model.Name)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Name)
    </div>
    <div class="display-label" style="font-size:20px;">
        @Html.DisplayNameFor(model => model.Address)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Address)
    </div>
    <div class="display-label" style="font-size:20px;">
        @Html.DisplayNameFor(model => model.ContactNo)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.ContactNo)
    </div>

</fieldset>
Edit.cshtml:
@model WvcCrudusingJqueryUI.Models.User
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User</legend>
        @Html.HiddenFor(model => model.UserID)

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ContactNo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ContactNo)
            @Html.ValidationMessageFor(model => model.ContactNo)
        </div>
        <p>
            <input type="submit" value="Save" />&nbsp;&nbsp;
            <input type="submit" value="Cancel" id="btncancel" />
        </p>
    </fieldset>
}
Step 3:
1.Now add below javascript code in index.cshtml file for popup functionality after the jquery libreary files. 
    var url = "";
    $(document).ready(function () {
        $("#alert-dialog").dialog({
            autoOpen: false,
            modal: true,
            draggable: false,
            resizable: false,
            open: function (event, ui) {
                $(".ui-dialog-titlebar-close").hide();
            },
            buttons: {
                "OK": function () { $(this).dialog("close"); },
                "Cancel": function () { $(this).dialog("close"); }
            }
        });
        $("#details-dialog").dialog({
            autoOpen: false,
            modal: true,
            draggable: false,
            resizable: false,
            open: function (event, ui) {
                $(".ui-dialog-titlebar-close").hide();
                $(this).load(url);
            },
            buttons: {
                "Close": function () { $(this).dialog("close"); }
            }
        });
        $("#create-dialog").dialog({
            title:"Create User",
            autoOpen: false,
            modal: true,
            resizable: false,
            width: 400,
            draggable: true,
            open: function (event, ui) {
                $(".ui-dialog-titlebar-close").hide();
                $(this).load(url);
            }
        });
        $("#delete-dialog").dialog({
            title: "Confirm Deletion of User",
            autoOpen: false,
            resizable: false,
            modal:true,
            draggable: true,
            open: function (event, ui) {
                $(".ui-dialog-titlebar-close").hide();
            },
            buttons: {
                "OK": function () {
                    $(this).dialog("close");
                    //to go to Delete action..
                    window.location.href = url;
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            }
        });
        if ('@TempData["msg"]' != "") {
            $("#alert-dialog").dialog("open");
        }       
        $("#lnkCreate").on("click", function (e) {
            //e.preventDefault();
            url = $(this).attr("href");
            $("#create-dialog").dialog("open");
         
            return false;
        });
        $(".lnkDetail").on("click", function (e) {
            url = $(this).attr("href");
            $("#details-dialog").dialog("open");
            return false;
        });
        $(".lnkEdit").on("click", function (e) {
            $(".ui-dialog-title").html("Update User");
            url = $(this).attr("href");
            $("#create-dialog").dialog("open");
            return false;
        });
        $(".lnkDelete").on("click", function (e) {
            url = $(this).attr("href");
            $("#delete-dialog").dialog("open");
            return false;
        });
        $("#btncancel").on("click", function (e) {
            $("#create-dialog").dialog("close");
            return false;
        });
    });
2.here we are invoking the jquery popups using .("selector").dialog() method.and on() method is used to add more events at a time.
3.Now run the application F5.


4.click on create New then create popup will come like this..

5.After saving the data in DB an alert box shows a message like 'data saved successfully'.


Step 4: Changing the dialog box styles
1.The above dialog box look like some old(not attractive).if you want to modify the colors of the dialogbox just give the option in dialog like "dialogClass:'some css class'".and paste the following styles code in the index view in </style> tag.
2.finally the dialog appears like this..


Download the Source code click Conclusion:
I hope this article helps you very much and you understand it well.If you suggest any modifications for this article please let me..

CRUD operations in ASP.NET MVC using Jquery,EF Part 1

02:06:00 Posted by raviteja swayampu , , No comments

CRUD operations using Jquery UI:

Introduction:
Hello every one welcome once again.Thanks for your comments for the last post.This article demonstrates "How to implement CRUD operations using Jquery(and Jquery UI also) in ASP.NET MVC with Entity framework".i hope every one knows about the jquery and jqueryUI those are javascript framework libraries for client side web development.Good thing about these is both are "open  source" tools(we need not to pay even a single penny to use).
coming to the article off-course i will explain in step by step manner.i always target the beginners of ASP.NET MVC.
Note: This is a very lengthy article that's why divided this article into two parts PART1 and PART2 for better readability.
Step 1: Create a Visual studio application and database

Note: In this article i am creating table in Sql server express which in-built integrated withVisual studio.If you want to use Another Sql server edition you can use.the procedure is same.

1.create a ASP.NET MVC application using Empty template.
2.right click on App_Start folder -->Add--.New Item-->Select Sql server database-->name it.

CRUD-operations-in-asp.netmvc-using-jquery

3.Create Table: click server explorer-->expand data connections-->expand Database.mdf(name of my database file i added in previous step)-->right click on Table-->Add New Table.then a table designer will appear.
4.create table with name "User".


5.click update button-->in 'Preview Database Updates' window click on "Update Database".
6.User Table created successfully.

Step 2: Add Model class in Model folder

1.right click Model folder-->Add-->New Item-->Select ADO.NET Entity Data Model-->name it Model.edmx.

CRUD-operations-in-asp.netmvc-using-jquery

2.In 'Entity Data Model wizard' select the option 'EF designer from Database'.then click Next

CRUD-operations-in-asp.netmvc-using-jquery
3.select the Database and name the connection string..

CRUD-operations-in-asp.netmvc-using-jquery
4.select the version of Entity Framework 5.0 (EF 6.0 or higher won't support scaffolding).next
5.Select the Table by expanding and click finish.
Now Model class and Context class are created successfully in the Models folder as shown in below.

CRUD-operations-in-asp.netmvc-using-jquery
5.Build the solution once..using Ctrl+Shift+B.

Step 3: Create a Controller

1.create controller and action method for CRUD(create,read,update,delete).
2.right click Controllers folder-->add-->controller-->name it HomeController-->Select 'Empty MVC Controller' from Dropdown. and click ok.
3.Replace HomeController code with following code.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WvcCrudusingJqueryUI.Models;
namespace WvcCrudusingJqueryUI.Controllers
{
    public class HomeController : Controller
    {
        DatabaseEntities db = new DatabaseEntities();
        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }
        public ActionResult Create()
        {
            return PartialView("Create");
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(User obj)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(obj);
                db.SaveChanges();
                TempData["msg"] = "Data saved successfully!";
                return RedirectToAction("Index");
            }
            return View();
        }
        public ActionResult Details(int id)
        {
            User record = new User();
            record=db.Users.Find(id);
            if (record == null)
            {
                return HttpNotFound();
            }
            return View(record);
        }
        [HttpGet]
        public ActionResult Edit(int id)
        {
            User record = db.Users.Find(id);
            if (record == null)
            {
                return HttpNotFound();
            }
            return View(record);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(User obj)
        {
            if (ModelState.IsValid)
            {
                db.Entry(obj).State = EntityState.Modified;
                db.SaveChanges();
                TempData["msg"] = "Data Updated Successfully!";
                return RedirectToAction("Index");
            }
            return View();
        }
        public ActionResult Delete(int id)
        {
            User obj = db.Users.Find(id);
            db.Users.Remove(obj);
            db.SaveChanges();
            TempData["msg"] = "Deleted Successfully";
            return RedirectToAction("index");
        }
    }
}

Step 3: Create Index view

1.Replace code code of Index view with following code
index.cshtml:
@model IEnumerable<WvcCrudusingJqueryUI.Models.User>
@{
    ViewBag.Title = "Index";
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

@* dialog box to diaplay create/edit dialog*@
<div id="create-dialog" style="display:none;"></div>
@* dialog box to diaplay alert after updation of values dialog*@
<div id="alert-dialog" style="display:none;">
    @TempData["msg"]
</div>
@* details dialog*@
<div id="details-dialog" style="display:none;"></div>
@* delete dialog box*@
<div id="delete-dialog" style="display:none">
    Do u want to delete user..
</div>
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create", null, new { id="lnkCreate"})
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ContactNo)
        </th>
        <th>
            Action Operations
        </th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ContactNo)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.UserID }, new { @class="lnkEdit"}) |
            @Html.ActionLink("Details", "Details", new { id = item.UserID }, new { @class = "lnkDetail" }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.UserID }, new {@class="lnkDelete" })
        </td>
    </tr>
}
</table>
2.Add Jquery libreary files in the Index page.
3.The highlighted <Div> elements to display the partial views like create.update,delete,details (don't worry partial views are nothing but UserControls in traditional ASP.NET Webforms.i will explain those Layout Views and partial views concept later.).
4.Below are links for CRUD operations.when user clicks on these links then popups will appear.

Next : CRUD operations in ASP.NET MVC using Jquery,EF Part 2

Conclusion:
I hope you understand this article.If you recommend any modifications please contact me i am always welcome.very soon i will post part2 article...

Wednesday, 30 March 2016

How to display popup in asp.net mvc using jquery

02:01:00 Posted by raviteja swayampu , No comments

How to create Modal popup in MVC:

Introduction:
Hi every one welcome again.How are you? .I hope you good. Just for change today we are going to learn a " How to create a modal popup window using jquery in MVC ". In real time applications we are not going to hit server every time every thing is done by jquery. The data transformation in ASP.NET MVC application is done by jquery or Angular js to increase the performance of the application and as well as reduce the burden on server.
In this article i will explain the simple example of model popup using jquery. For this we need to add javascript libreary in MVC application.

What is Jquery: 

 Jquery is javascript libreary. it is a framework which simplifies the usage of javascript by implementing some predefined code.for example we need to write lot's of code in code in javascript for ajax but it can be achieved by 2 or 3 lines of code in jquery. it reduces the code and reduces the burdon on developer.
ajax code in javascript:

 //ajax code in jquery:
function loadDoc() {
  var xhttp;
  if (window.XMLHttpRequest) {
    // code for modern browsers
    xhttp = new XMLHttpRequest();
    } else {
    // code for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}
//in jquery code is like this
 $.ajax({url: "demo_ajax_load.txt", async: false, success: function(result){
            $("div").html(result);
        }});

  I think now you know the power of jquery in web development. I will come to the article now creating modal popup.i will explain it step by step manner.
Step 1:
Create a ASP.NET application:
1.Add Controller and name it HomeController.
2.Add view for Index ActionMethod.
3.Add jquery library files in the Index page like below.

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
4.create sample button "click me".
Step 2: Modify the Index view.
1.Index.cshtml view after modifications done..
@{
    ViewBag.Title = "Jquery modal popup";
}
<h2>Jquery popup</h2>
@*Add Jquery librearies--jquery CDN library links*@
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
    $(document).ready(function () {      
            $("#source").dialog({
            autoOpen: false,
            title:"Basic popup",
            show: {
                effect: "blind",
                duration:"1000"
            },
            hide: {
                effect: "explode",
                duration:"1000"
            }
            });
            $("#btnClickMe").click(function () {
                $("#source").dialog("open");
            });
    });
</script>
<button type="button" id="btnClickMe">Click Me</button>

<div id="source">
    <p>
   Hello every one this is a sample popup!
   </p>
</div>

2.we can set the options like title options and also contains methods like "open" to the modal popup.
title: specifies title of popup
3.when i click on button modal popup will appear."autoOpen:false" prevent the default behavior of popup(generally opens after window loading).
4.For more options and methods goto this link.
5. Now run the application

Modal-popup-using-jquery-in-mvc
6.Here the text should not appear like this and when i click on the button popup is not coming.If u got this situation just goto the _Layout.cshtml and comment <script> file that references jquery.

7.Now again run the application you will get window like this we you click on buttion.

Modal-popup-using-jquery-in-mvc-demo
Step 3:
applying styles to the popup windows:
if you want to add styles to modal popup then use "dialogClass" option and specify name of the class.
ex:
$('#success').dialog({
    height: 50,
    width: 350,
    modal: true,
    resizable: true,
    dialogClass: 'no-close success-dialog'     //custom theming classes for dialog
});
Conclusion:
I hope you understand the tutorial . if you recommend any modifications please let me know.do u have any doubts i am here to help you...


Tuesday, 29 March 2016

Implementing Paging in ASp.NET MVC

21:34:00 Posted by raviteja swayampu No comments
Introduction:
Hello every one.how are you? i hope you all are fine. In this article i am going to tell you "How to implement paging in MVC4".I hope you gone through my previous articles . You will get better understanding of basic concepts in MVC if you gone through my previous articles.For this article i created application "filteringinmvc"(actually i am using previous article code to save the time).
Step 1:
Create an CRUD applications as shown:


Step 2:
Install the PagedList.Mvc package from Nuget pakage manager console.
goto menu-->Tools-->Nuget package manager console-->Package manager console and paste the command and press enter.

  • Install-Package PagedList.Mvc
Now open the EmployeeController and modify the code as below.

 public ActionResult Index(string SearchString,string sortOrder,string currentFilter,int? page)
        {
            var contacts = from c in db.Employees
                           select c;
            if (!String.IsNullOrEmpty(SearchString)) {
                contacts = contacts.Where(s=>s.FirstName.Contains(SearchString));
            }
            ViewBag.currentSort = sortOrder;
            ViewBag.NameSortParam = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParam = sortOrder == "Date" ? "date_desc" : "Date";

            if (SearchString != null)
            {
                page = 1;
            }
            else
            {
                SearchString = currentFilter;
            }

            ViewBag.CurrentFilter = SearchString;
            switch (sortOrder) {
                case "name_desc":
                    contacts = contacts.OrderByDescending(x => x.FirstName);
                    break;
                case "Date":
                    contacts = contacts.OrderBy(x => x.DateOfBirth);
                    break;
                case "date_desc":
                    contacts = contacts.OrderByDescending(x => x.DateOfBirth);
                    break;
                default:
                    contacts = contacts.OrderBy(x => x.LastName);
                    break;
            }
            int pageSize = 3;
            int pageNumber = (page ?? 1);
            return View(contacts.ToPagedList(pageNumber,pageSize));
        }

Those two parameters CurrentFilter, page values come from View. If page loads first time default paging is based on sortOrder. if user enters any searchString when requested only opened with paging index one. otherwise paging links will be shown in the page.

Step 3:
Create paging links in Index.cshtml:
open the Index.cshtml and modify view code based on the following...

@model PagedList.IPagedList<Filteringinmvc.Models.Employee>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
    @using (Html.BeginForm()) {
    <p>
        First Name:@Html.TextBox("SearchString")
        <input type="submit" value="Search" />
    </p>
}
</p>
<table class="table">
    <tr>
        <th>
            @Html.ActionLink("First Name","Index",new { sortOrder=ViewBag.NameSortParam})
        </th>
        <th>
           @Html.ActionLink("Last Name", "Index")  
        </th>
        <th>
           @Html.ActionLink("DateOf Birth", "Index", new { sortOrder = ViewBag.DateSortParam })
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.DateOfBirth)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}
</table>
<br/>
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

The using statement is used to access the PagedList.Mvc. That contains the functionality of paging links.We specified @model directive to access the paged object values in the view.
Run the application press F5.


Conclusion:
I tried as much as possible to simply make you understand using simple steps.If u have any doubts you can ask me and this article needs any modification for better understanding please let me know.i always welcome you ..

Monday, 28 March 2016

Implementing sorting in ASP.NET MVC

03:51:00 Posted by raviteja swayampu No comments
Introduction:
Hi every one welcome again.thank you for your great response to the previous post Searching in ASP.NET MVC .Now in this article i am going to tell you how to add sorting functionality to the application using Entity framework and LINQ. This article is better understandable for the people who gone through my previous post.

For this article i created a sample application with name "Filteringinmvc". After running the application the window will look like this..



Step 1: Add sorting functionality to Index method:
To add sorting to the Index page we shall change the Index method of the employeesController class.
with following code.

Controller/employeesController.cs:

 public ActionResult Index(string SearchString,string sortOrder)
        {
            var contacts = from c in db.Employees
                           select c;
            if (!String.IsNullOrEmpty(SearchString)) {
                contacts = contacts.Where(s=>s.FirstName.Contains(SearchString));
            }

            ViewBag.NameSortParam = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParam = sortOrder == "Date" ? "date_desc" : "Date";

            switch (sortOrder) {
                case "name_desc":
                    contacts = contacts.OrderByDescending(x => x.FirstName);
                    break;
                case "Date":
                    contacts = contacts.OrderBy(x => x.DateOfBirth);
                    break;
                case "date_desc":
                    contacts = contacts.OrderByDescending(x => x.DateOfBirth);
                    break;
                default:
                    contacts = contacts.OrderBy(x => x.LastName);
                    break;
            }

            return View(contacts);
        }

Note: Here the default sorting is done by 'LastName' in ascending order.The above action method receives sortOrder parameter from query string in the url.This query string value is provided by the ASP.NET MVC as a parameter to the action method.The parameter may be 'string' or "Date".for the first time there is no parameter then default ascending order of "LastName" is displayed.when user clicks on the action links then appropriate sorting order is displayed according to the query string.

Step 2: Change the Index View:

Implementing sorting in ASP.NET MVC
Then the application the window will be like this

Implementing sorting in ASP.NET MVC
In the above you can see the query string when user clicks on 'First Name'.The url look like this
http://localhost:56801/?sortOrder=name_desc
when user clicks on DateOfBirth then url will be
http://localhost:56801/?sortOrder=Date

Download the source code from HERE Conclusion: 
I hope you guys enjoyed my article.You need any answers please contact me..


Sunday, 27 March 2016

Implementing searching functionality in ASP.NET MVC Application

21:50:00 Posted by raviteja swayampu , 2 comments

Searching in ASP.NET MVC Using Entity framework:

Introduction:
Hello every one welcome once again thanks for the previous post comments.In this post we are going to learn how to create search functionality in MVC application using Entity framework(Object relational mapping tool for database operations) and LINQ (Language integrated Query).i will explain about both these thing later in next posts.


I will explain this tutorial in a step by step manner.
Step 1: Open Visual studio and create ASP.NET MVC application using Empty template

Searching in ASP.NET MVC Application

Step 2:
1.Create a table in the database by using Sql server express Local Db(if u have Sqlserver 2008/2012 u can create tables in those).
2.Creating table in LocalDb:
   Add Server file(.mdf file) in App_Start folder (right click on App_Start-->Add-->New Item--    >Choose "Data" on left side -->select Sql server database-->name it as "Search.mdf").
3.Adding Table:
   open server explorer-->expand Data Connections-->Expand Search.mdf-->right click tables folder--> Add New table.
Then table designer loads and create table with name it as Employee .

Searching in ASP.NET MVC Application
then click on update-->in new window click on Update database button then table created.

Searching in ASP.NET MVC Application

Step 3:
1.Create model classes using ADO.NET Entity Model
right click on models folder-->Add-->New Item-->Choose Data from left side-->select ADO.NET Entity Data Model-->name it Model.edmx-->click Add button.

Searching in ASP.NET MVC Application

2.choose Model from database

Searching in ASP.NET MVC Application

3.select Search.mdf in dropdown and name the connection string below.

Searching in ASP.NET MVC Application

4.Select the version of Entity framework here

Searching in ASP.NET MVC Application

5.select the table from the Database and click Finish.

Searching in ASP.NET MVC Application

6.Edmx file created with model class and context class as shown and don't worry about the other files in the folder..

Searching in ASP.NET MVC Application

Step 4: Now it's time to create a controller right click controller folder-->Add-->Controller-->name it EmployeeController.(Just build the solution once for scaffolding.)
1.Select MVC5 Controller with View,using Entity framework.

Searching in ASP.NET MVC Application

2.Select Model and context class

Searching in ASP.NET MVC Application

3.Click on Add then visual studio automatically creates all the Controller action methods and Corresponding Views as shown below.
Searching in ASP.NET MVC Application

4.Controller code is as follows
EmployeeController.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Searchinginmvc.Models;

namespace Searchinginmvc.Controllers
{
    public class employeesController : Controller
    {
        private SearchEntities db = new SearchEntities();

        // GET: employees
        public ActionResult Index()
        {
            return View(db.employees.ToList());
        }

        // GET: employees/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            employee employee = db.employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // GET: employees/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: employees/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,Address,Designation")] employee employee)
        {
            if (ModelState.IsValid)
            {
                db.employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(employee);
        }

        // GET: employees/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            employee employee = db.employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: employees/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,Address,Designation")] employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        // GET: employees/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            employee employee = db.employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: employees/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            employee employee = db.employees.Find(id);
            db.employees.Remove(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

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

The output for the application is as follows (run the application using F5).

Searching in ASP.NET MVC Application

we got the above error "The resource can not be found".if u got this type of error go to the route.cs file.we need to configure the route config file before we run the application.do the following modifications in the route.cs file.

Searching in ASP.NET MVC Application

now again run the application once

Searching in ASP.NET MVC Application

Step 5:
1.Implement search functionality:
if we want to implement the search functionality we need to change the Index action method in the "employeesController".

Searching in ASP.NET MVC Application
2.Now modify the index.cshtml page also to add the search textbox and filter button.
index.cshtml:
<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<p>
@using (Html.BeginForm()) {
   <p>Name: @Html.TextBox("searchstring")
    <input type="submit" value="Filter" /></p>
}
</p>

3.Now run the application using F5 and the output will be like this..

Searching in ASP.NET MVC Application
4.Now enter any name of the contact for ex: Raviteja and press Filter button then it will appear like this.now you can any Name in the data below.

Searching in ASP.NET MVC Application

5.And can also add another serch method using Dropdownlist

employeesController.cs:

public ActionResult Index(string searchstring,string designation)
      {
            //import all the contacts from db into 'contacts'variable
            //this expressions are written in LINQ(language integrated query)
            var contacts = from c in db.employees
                           select c;
            var DesigList = new List();
            var desigQuery = from d in db.employees
                              orderby d.Designation
                              select d.Designation;

            DesigList.AddRange(desigQuery.Distinct());
            ViewBag.Desig = new SelectList(DesigList);

            //filtering data based on search string..
            if (!String.IsNullOrEmpty(searchstring)) {
                contacts = contacts.Where(s => s.Name.Contains(searchstring));
            }
            if (!String.IsNullOrEmpty(designation)) {
                contacts = contacts.Where(x => x.Designation == designation);
            }

            return View(contacts);
        }

6.change the index.cshtml page also with following code

Searching in ASP.NET MVC Application
7.Run the application and check output by selecting on the value from Dropdownlist like below.

Searching in ASP.NET MVC Application

You can check the output by giving another values also..

Download the code for this post: click here
Note: This code for reference only.My sincere advice is 'try a new application on your own it will help full for you to learn subject'.

I hope you enjoyed and learned how searching functionality is implemented.if you have any doubts please ask me i am always ready to help you..

Saturday, 26 March 2016

CRUD operations in ASP.NET MVC using ADO.NET

07:38:00 Posted by raviteja swayampu No comments

Introduction:

Hello every one welcome again.In this tutorial we are going to learn the CRUD operations is ASP.NET MVC. It is a hot technology in now a days.This post will target the beginners of ASP.NET MVC. Thanks for comments and likes for the previous article "CRUD operations in ASP.NET MVC using ADO.NET".Some of the friends asked me same post using ADO.NET .that why i am posting this.If you are the beginner to MVC it's the better start with the basics .just follow the below links.
Create a project in Visual studio 2013
1.I am going to explain this in step by step manner for better understanding and readability.

CRUD operations in ASP.NET MVC using ADO.NET

2.Now a Empty ASP.NET MVC project is created with some folders like below

CRUD operations in ASP.NET MVC using ADO.NET

Step 2:
Create model class in Model folder and name it as EmpModel.cs.We can create model class any where in the solution explorer for better readability and maintainability of the project just place it in the Models folder only.follow below screenshot

CRUD operations in ASP.NET MVC using ADO.NET

EmpModel.cs code:

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

namespace Ado.netapplication.Models
{
    public class EmpModel
    {
        [Display(Name = "Id")]
        public int Empid { get; set; }

        [Required(ErrorMessage = "First name is required.")]
        public string Name { get; set; }

        [Required(ErrorMessage = "City is required.")]
        public string City { get; set; }

        [Required(ErrorMessage = "Address is required.")]
        public string Address { get; set; }

    }
}
Note:We have added some validations to the properties those are called "Data Annotations".which are present in namespace "System.ComponentModel.DataAnnotations".

Step 3:Create a Controller class

CRUD operations in ASP.NET MVC using ADO.NET


Note:Controller name must have prefix "Controller" because it required for the ASP.NET MVC execution engine to differentiate the model classes with Controller classes.

Step 4: Create Table and Stored procedures
1.create a table with the name "Employee".

CRUD operations in ASP.NET MVC using ADO.NET

2.Add Sql server file "Database.mdf" and create table

CRUD operations in ASP.NET MVC using ADO.NET

create table


3.Now create stored procedures to insert,update,delete,create
Insert Records:


Create procedure [dbo].[AddNewEmpDetails]  
(  
   @Name varchar (50),  
   @City varchar (50),  
   @Address varchar (50)  
)  
as  
begin  
   Insert into Employee values(@Name,@City,@Address)  
End 

To View Records:
Create Procedure [dbo].[GetEmployees]  
as  
begin  
   select *from Employee  
End

Update records:
Create procedure [dbo].[UpdateEmpDetails]  
(  
   @EmpId int,  
   @Name varchar (50),  
   @City varchar (50),  
   @Address varchar (50)  
)  
as  
begin  
   Update Employee   
   set Name=@Name,  
   City=@City,  
   Address=@Address  
   where Id=@EmpId  
End 

Delete records:
Create procedure [dbo].[DeleteEmpById]  
(  
   @EmpId int  
)  
as   
begin  
   Delete from Employee where Id=@EmpId  
End 

Step 5:create a Repository class
Now create a repository class that contains the server operations.


EmpRepository.cs:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using CRUDUsingMVC.Models;
using System.Linq;
namespace CRUDUsingMVC.Repository
{
    public class EmpRepository
    {
        private SqlConnection con;
        //To Handle connection related activities
        private void connection()
        {
            string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
            con = new SqlConnection(constr);
        }
        //To Add Employee details
        public bool AddEmployee(EmpModel obj)
        {
            connection();
            SqlCommand com = new SqlCommand("AddNewEmpDetails", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Name", obj.Name);
            com.Parameters.AddWithValue("@City", obj.City);
            com.Parameters.AddWithValue("@Address", obj.Address);
            con.Open();
            int i = com.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        //To view employee details with generic list 
        public List GetAllEmployees()
        {
            connection();
            List EmpList =new List();
            SqlCommand com = new SqlCommand("GetEmployees", con);
            com.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataTable dt = new DataTable();
            con.Open();
            da.Fill(dt);
            con.Close();
            //Bind EmpModel generic list using LINQ 
            EmpList = (from DataRow dr in dt.Rows

                       select new EmpModel()
                       {
                           Empid = Convert.ToInt32(dr["Id"]),
                           Name = Convert.ToString(dr["Name"]),
                           City = Convert.ToString(dr["City"]),
                           Address = Convert.ToString(dr["Address"])
                       }).ToList();
            return EmpList;
        }
        //To Update Employee details
        public bool UpdateEmployee(EmpModel obj)
        {
            connection();
            SqlCommand com = new SqlCommand("UpdateEmpDetails", con);
           
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@EmpId", obj.Empid);
            com.Parameters.AddWithValue("@Name", obj.Name);
            com.Parameters.AddWithValue("@City", obj.City);
            com.Parameters.AddWithValue("@Address", obj.Address);
            con.Open();
            int i = com.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
            {        
                return true;
            }
            else
            {
                return false;
            }
        }
        //To delete Employee details
        public bool DeleteEmployee(int Id)
        {
            connection();
            SqlCommand com = new SqlCommand("DeleteEmpById", con);

            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@EmpId", Id);
           
            con.Open();
            int i = com.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
            {
               
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

Step 5:Create controller action methods for Create,Delete,update,Select

EmployeeController.cs code:

public class EmployeeController : Controller    
    {             
        // GET: Employee/GetAllEmpDetails    
        public ActionResult GetAllEmpDetails()    
        {                 
            EmpRepository EmpRepo = new EmpRepository();    
            ModelState.Clear();    
            return View(EmpRepo.GetAllEmployees());    
        }    
        // GET: Employee/AddEmployee    
        public ActionResult AddEmployee()    
        {    
            return View();    
        }         
        // POST: Employee/AddEmployee    
        [HttpPost]    
        public ActionResult AddEmployee(EmpModel Emp)    
        {    
            try    
            {    
                if (ModelState.IsValid)    
                {    
                    EmpRepository EmpRepo = new EmpRepository();    
      
                    if (EmpRepo.AddEmployee(Emp))    
                    {    
                        ViewBag.Message = "Employee details added successfully";    
                    }    
                }    
                  
                return View();    
            }    
            catch    
            {    
                return View();    
            }    
        }    
      
        // GET: Employee/EditEmpDetails/5    
        public ActionResult EditEmpDetails(int id)    
        {    
            EmpRepository EmpRepo = new EmpRepository();    
      
              
      
            return View(EmpRepo.GetAllEmployees().Find(Emp => Emp.Empid == id));    
      
        }    
      
        // POST: Employee/EditEmpDetails/5    
        [HttpPost]    
          
        public ActionResult EditEmpDetails(int id,EmpModel obj)    
        {    
            try    
            {    
                    EmpRepository EmpRepo = new EmpRepository();    
                      
                    EmpRepo.UpdateEmployee(obj);       
      
                return RedirectToAction("GetAllEmpDetails");    
            }    
            catch    
            {    
                return View();    
            }    
        }    
      
        // GET: Employee/DeleteEmp/5    
        public ActionResult DeleteEmp(int id)    
        {    
            try    
            {    
                EmpRepository EmpRepo = new EmpRepository();    
                if (EmpRepo.DeleteEmployee(id))    
                {    
                    ViewBag.AlertMsg = "Employee details deleted successfully";    
      
                }    
                return RedirectToAction("GetAllEmpDetails");    
      
            }    
            catch    
            {    
                return View();    
            }    
        }                 
    }    
Step:7
Create Views for the Controller Action methods
Click on Action methods and create partial strongly typed views for the action methods
right click any where on the action methods  select the templates and model class and click on "Add".Then strongly typed views generate like below with code.

CRUD operations in ASP.NET MVC using ADO.NET

AddEmployee.cshtml:
@model CRUDUsingMVC.Models.EmpModel 

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 



    <div class="form-horizontal"> 

        <h4>Add Employee</h4> 

        <div> 

            @Html.ActionLink("Back to Employee List", "GetAllEmpDetails") 

        </div> 

        <hr /> 

        @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 



        <div class="form-group"> 

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) 

            <div class="col-md-10"> 

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) 

                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" }) 

            </div> 

        </div> 



        <div class="form-group"> 

            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" }) 

            <div class="col-md-10"> 

                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } }) 

                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" }) 

            </div> 

        </div> 



        <div class="form-group"> 

            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" }) 

            <div class="col-md-10"> 

                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } }) 

                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" }) 

            </div> 

        </div> 



        <div class="form-group"> 

            <div class="col-md-offset-2 col-md-10"> 

                <input type="submit" value="Save" class="btn btn-default" /> 

            </div> 

        </div> 

        <div class="form-group"> 

            <div class="col-md-offset-2 col-md-10" style="color:green"> 

                @ViewBag.Message 



            </div> 

        </div> 

    </div> 



}  

<script src="~/Scripts/jquery-1.10.2.min.js"></script> 

<script src="~/Scripts/jquery.validate.min.js"></script> 

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>


GetallEmployees:
To see the inserted the value create a GetallEmployees.cshtml

GetAllEmployeeDetails.cshtml:

@model IEnumerable<CRUDUsingMVC.Models.EmpModel> 



<p> 

    @Html.ActionLink("Add New Employee", "AddEmployee") 

</p> 



<table class="table"> 

    <tr> 



        <th> 

            @Html.DisplayNameFor(model => model.Name) 

        </th> 

        <th> 

            @Html.DisplayNameFor(model => model.City) 

        </th> 

        <th> 

            @Html.DisplayNameFor(model => model.Address) 

        </th> 

        <th></th> 

    </tr> 



    @foreach (var item in Model) 

    { 

        @Html.HiddenFor(model => item.Empid) 

        <tr> 



            <td> 

                @Html.DisplayFor(modelItem => item.Name) 

            </td> 

            <td> 

                @Html.DisplayFor(modelItem => item.City) 

            </td> 

            <td> 

                @Html.DisplayFor(modelItem => item.Address) 

            </td> 

            <td> 

                @Html.ActionLink("Edit", "EditEmpDetails", new { id = item.Empid }) | 

                @Html.ActionLink("Delete", "DeleteEmp", new { id = item.Empid }, new { onclick = "return confirm('Are sure wants to delete?');" }) 

            </td> 

        </tr> 



    } 

</table>

Update Employees:

Follow the same procedure and create EditEmpDetails view to edit the employees. After creating the view the code will be like the following

EditEmpDetails.cshtml:

@model CRUDUsingMVC.Models.EmpModel 

@using (Html.BeginForm()) 

{ 

    @Html.AntiForgeryToken() 



    <div class="form-horizontal"> 

        <h4>Update Employee Details</h4> 

        <hr /> 

        <div> 

            @Html.ActionLink("Back to Details", "GetAllEmployees") 

        </div> 

        <hr /> 

        @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 

        @Html.HiddenFor(model => model.Empid) 



        <div class="form-group"> 

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) 

            <div class="col-md-10"> 

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) 

                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" }) 

            </div> 

        </div> 



        <div class="form-group"> 

            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" }) 

            <div class="col-md-10"> 

                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } }) 

                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" }) 

            </div> 

        </div> 



        <div class="form-group"> 

            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" }) 

            <div class="col-md-10"> 

                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } }) 

                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" }) 

            </div> 

        </div> 



        <div class="form-group"> 

            <div class="col-md-offset-2 col-md-10"> 

                <input type="submit" value="Update" class="btn btn-default" /> 

            </div> 

        </div> 

    </div> 

} 

<script src="~/Scripts/jquery-1.10.2.min.js"></script> 

<script src="~/Scripts/jquery.validate.min.js"></script> 

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Step 8:

Finally Configure the Routing.cs file for the default routing page.

public class RouteConfig
 {
     public static void RegisterRoutes(RouteCollection routes)
     {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapRoute(
             name: "Default",
             url: "{controller}/{action}/{id}",
             defaults: new { controller = "Employee", action = "AddEmployee", id = UrlParameter.Optional }
         );
     }
 }

Here we set the default action as "AddEmployee" in route.config that means when we run the application it will opens.
Configure the Edit and Delete action links in "GetAllEmpDetails" page for doing this edit and delete actions


Run the application and see the output
if u have doubts feel free to ask me.

Download code