Home > DeveloperSection > Beginner > ASP.NET MVC5 Razor With jQuery

ASP.NET MVC5 Razor With jQuery


ASP.Net C#  ASP.Net  JQuery  JavaScript  HTML  ASP.NET MVC  View  Model  Controller  Razor 
Ratings:
0 Comment(s)
 937  View(s)
Rate this:

ASP.NET MVC5 Razor With jQuery


Introduction:

 

In this article I will take a simplest way to create a simple MVC 5 application for beginners. If you are a beginner and want to be find how to create modal, controller and their views with extra plugins such as jQuery. If you are not comfortable with jQuery so, don’t worry you have skip those topic and concentrate with rest one.

In this article, I have explain about how to create a modal, how to create a controller & How to bind their views with its data modal. I have also using a jQuery for extra enhancements.

 

 

Background:

 

MVC is a Framework which is use for building a web application with the facilitate of MVC Design. It’s 100% extensible.

Here are three patterns for implemented and design for MVC Application.

   Model:  The Model pattern will handled the logic of the application data. A model is easy to get both controller and view. Pass the data from controller to view by the Model.

   View: The view pattern exhibit the user interface of an application. This interface shaped with the Model data.

    Controller: The controllers will interaction with the user request. Controller watch out the whole execution of request. It’s got the request from the web server and checks the data necessities.

 

  Model:


   I have using a code first approach for creating a model. Here, I have created an Employee model. For creating an employee model. Follow the following steps:


 1.      Right click on Model Folder

2.      Choose “Add” navigation

3.      Choose “Class” and Select

4.      Renaming the class file name “Employee”

5.      Then paste the below code

 

 

   

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace Demo.Models
{
    public class Employee
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int EmpID { get; set; }
        [Required]
        [Display(Name="Full Name")]
        public string FullName { get; set; }
        [Required]
        [Display(Name="Email-id")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters  long.", MinimumLengt h = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
        [Display(Name="Date-Of-Birth")]
        public DateTime DoB { get; set; }
        [Display(Name="Address")]
        public string Address { get; set; }
        [Display(Name="City")]
        public string Town { get; set; }
        [Display(Name="Country")]
        public string County { get; set; }
        [Display(Name="IsActive")]
        public bool IsActive { get; set; }
}
    public class EmployeeDBContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
}

 

 

Controller:

     

   Here, I have created an EmployeeController. For creating an EmployeController. Follow the following steps:


1.      Right click on Controller Folder

2.      Choose “Add” navigation

3.      Choose “Controller” and Select

4.      Renaming the Controller file name “EmployeeController”

5.      In Scaffolding Option choose template “MVC controller with read/write actions and views,using             Entity Framework

6.      Select Model class “Employee(****.Models)

7.      Choose Data Context class :”EmployeeDBContext(****.Models)

8.      View is by default Razor and other one remaining same.

9.      Click add button

***** representing your namespace


Views:

It will created a folder with the same name as controller name  in Views section and it will also create 5 views namely Index, Create, Edit, Delete, Details automatically. Such as look like this:




 Index Page:

 Here, it is a simple index page that are display records and attached with other views of loaded functionality for curd operation.

@model IEnumerable<Demo.Models.Employee>
 
@{
    ViewBag.Title = "Index";
}
 
<h2>Index</h2>
 
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model=> model.FullName)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Email)
        </th>
         <th>
            @Html.DisplayNameFor(model=> model.DoB)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Town)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.County)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.IsActive)
        </th>
        <th></th>
    </tr>
 
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem=> item.FullName)
        </td>
        <td>
            @Html.DisplayFor(modelItem=> item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem=> item.DoB)
        </td>
        <td>
            @Html.DisplayFor(modelItem=> item.Address)
        </td>
        <td>
            @Html.DisplayFor(modelItem=> item.Town)
        </td>
        <td>
            @Html.DisplayFor(modelItem=> item.County)
        </td>
        <td>
            @Html.DisplayFor(modelItem=> item.IsActive)
        </td>
        <td>
            @Html.ActionLink("Edit","Edit", new { id=item.EmpID }) |
            @Html.ActionLink("Details", "Details", new { id=item.EmpID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.EmpID })
        </td>
    </tr>
}
 
</table>
 

 

Output:




Search:

The search functionality for searching employee with name and its other related areas.

Now, I applied some jQuery code for better look & feel and using html for data will be inside a table. Here, the code of searching and some basic filtering in action result Index of EmployeeController. Code is as follows:

public ActionResult
Index(string searchString,string currentFilter,string sortOrder)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm =sortOrder == "Date" ? "date_desc" : "Date";
            ViewBag.CurrentFilter= searchString;
            var emp = from s in db.Employees
                           select s;
            if (!String.IsNullOrEmpty(searchString))
            {
                emp = emp.Where(s=> s.FullName.ToUpper() .Contains(searchString.ToUpper())
                   || s.Email.ToUpper().Contains(searchString.ToUpper()) ||s.Address.ToUpper().Contains(searchString.ToUpper()) ||s.County.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "name_desc":
                    emp = emp.OrderByDescending(s => s.FullName);
                    break;
                 case "date_desc":
                    emp = emp.OrderByDescending(s => s.DoB);
                    break;
                default//Name ascending
                    emp = emp.OrderBy(s => s.EmpID);
                    break;
            }
              return View(emp.ToList());
        }

 

Index.cshtml

@model IEnumerable<Demo.Models.Employee>
 
@{
    ViewBag.Title = "Employee Home";
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.8.24.js"></script>
<h2>Home</h2>
 
<p>
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    @using (Html.BeginForm("Create", "Employee"))
    {
   
        <input type="submit" value="Create New Employee" style="padding: 5px 5px 5px 5px" />
        
    }
</p>
 @using (Html.BeginForm("Index", "Employee", FormMethod.Get))
{
    <p >
       Search: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string
        <input type="submit" value="Search" />
    </p>
}
 
<table id="emp">
    <tr>
        <th>
            @Html.ActionLink("Full Name", "Index", new { sortOrder = ViewBag.NameSortParm })
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Email))
        </th>
        <th>
            @Html.ActionLink("D-O-B","Index", new { sortOrder = ViewBag.DateSortParm })
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Town)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.County)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.IsActive)
        </th>
        <th>Actions
        </th>
 
    </tr>
 
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem=> item.FullName)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.Email)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.DoB)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.Town)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.County)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.IsActive)
            </td>
            <td>
            @Html.ActionLink("Edit","Edit", new { id = item.EmpID }) |
            @Html.ActionLink("Details", "Details", new { id = item.EmpID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.EmpID })
            </td>
        </tr>
     
    }
 
</table>
  @Url.Action("Index", new { sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter });
<style>
    table #emp {
        width:initial;
        background-color:#f1f1c1;
        position:absolute;
    }
 
        table #emp tr:nth-child(even) {
            background-color:#ccc;
        }
 
        table #emp tr:nth-child(odd) {
            background-color: #fff;
        }
 
        table #emp th {
            color:black;
            background-color:yellow;
        }
 
    table, th, td {
        border:2px solid black;
    }
 
    table, th, td {
        border:1px solid black;
        border-collapse: collapse;
    }
 
    table, th, td {
        border:1px solid black;
        border-collapse: collapse;
    }
 
    th, td {
        padding: 5px;
    }
 
  
</style>
 

 

 

 Output:


After searching operation, output is as follow:



References:

·                 Working with Model

·         Working with Controller

·         https://jquery.com/

·         http://www.asp.net/mvc/mvc5


Don't want to miss updates? Please click the below button!

Follow MindStick