ASP.NET MVC scaffolding provides a quick way to generate the CRUD operations in a standardized way, creating the necessary logic that lets your application interact with the database layer. in this post, explained with example for how to use scaffolding.

Create new employee table with existing/new sql database

We created new table Emplyoyee in sql DB and this table will be used for Scaffolding.

Create New Project

created the project with name MvcScaffolding with basic template

Create the edmx file

Step 1

Step 2

Step 3

Step 4

Step 5

Step 6

This edmx created and included newly created employee table also.we will use this edmx for scaffolding

Create the controller

created the new controller with name Employee and used the template read/write actions,views using entity framework

After Created the controller using scaffolding

Index.cshtml file

Code Snippet
  1. @model IEnumerable<MvcScaffolding.Employee>
  2.  
  3. @{
  4.     ViewBag.Title = "Index";
  5. }
  6.  
  7. <h2>Index</h2>
  8.  
  9. <p>
  10.     @Html.ActionLink("Create New", "Create")
  11. </p>
  12. <table>
  13.     <tr>
  14.         <th>
  15.             @Html.DisplayNameFor(model => model.EmpId)
  16.         </th>
  17.         <th>
  18.             @Html.DisplayNameFor(model => model.EmployeeName)
  19.         </th>
  20.         <th>
  21.             @Html.DisplayNameFor(model => model.Position)
  22.         </th>
  23.         <th>
  24.             @Html.DisplayNameFor(model => model.CityID)
  25.         </th>
  26.         <th></th>
  27.     </tr>
  28.  
  29. @foreach (var item in Model) {
  30.     <tr>
  31.         <td>
  32.             @Html.DisplayFor(modelItem => item.EmpId)
  33.         </td>
  34.         <td>
  35.             @Html.DisplayFor(modelItem => item.EmployeeName)
  36.         </td>
  37.         <td>
  38.             @Html.DisplayFor(modelItem => item.Position)
  39.         </td>
  40.         <td>
  41.             @Html.DisplayFor(modelItem => item.CityID)
  42.         </td>
  43.         <td>
  44.             @Html.ActionLink("Edit", "Edit", new {  id=item.EmpId  }) |
  45.             @Html.ActionLink("Details", "Details", new {id=item.EmpId }) |
  46.             @Html.ActionLink("Delete", "Delete", new { id=item.EmpId })
  47.         </td>
  48.     </tr>
  49. }
  50.  
  51. </table>

Details.cshtml file

Code Snippet
  1. @model MvcScaffolding.Employee
  2.  
  3. @{
  4.     ViewBag.Title = "Details";
  5. }
  6.  
  7. <h2>Details</h2>
  8.  
  9. <fieldset>
  10.     <legend>Employee</legend>
  11.  
  12.     <div class="display-label">
  13.          @Html.DisplayNameFor(model => model.EmpId)
  14.     </div>
  15.     <div class="display-field">
  16.         @Html.DisplayFor(model => model.EmpId)
  17.     </div>
  18.  
  19.     <div class="display-label">
  20.          @Html.DisplayNameFor(model => model.EmployeeName)
  21.     </div>
  22.     <div class="display-field">
  23.         @Html.DisplayFor(model => model.EmployeeName)
  24.     </div>
  25.  
  26.     <div class="display-label">
  27.          @Html.DisplayNameFor(model => model.Position)
  28.     </div>
  29.     <div class="display-field">
  30.         @Html.DisplayFor(model => model.Position)
  31.     </div>
  32.  
  33.     <div class="display-label">
  34.          @Html.DisplayNameFor(model => model.CityID)
  35.     </div>
  36.     <div class="display-field">
  37.         @Html.DisplayFor(model => model.CityID)
  38.     </div>
  39. </fieldset>
  40. <p>
  41.     @Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
  42.     @Html.ActionLink("Back to List", "Index")
  43. </p>

Employee Controller

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.Entity;
  5. using System.Linq;
  6. using System.Web;
  7. using System.Web.Mvc;
  8.  
  9. namespace MvcScaffolding.Controllers
  10. {
  11.     public class EmployeeController : Controller
  12.     {
  13.         private TestDBEntities db = new TestDBEntities();
  14.  
  15.         //
  16.         // GET: /Employee/
  17.  
  18.         public ActionResult Index()
  19.         {
  20.             return View(db.Employees.ToList());
  21.         }
  22.  
  23.         //
  24.         // GET: /Employee/Details/5
  25.  
  26.         public ActionResult Details(int id = 0)
  27.         {
  28.             Employee employee = db.Employees.Find(id);
  29.             if (employee == null)
  30.             {
  31.                 return HttpNotFound();
  32.             }
  33.             return View(employee);
  34.         }
  35.  
  36.         //
  37.         // GET: /Employee/Create
  38.  
  39.         public ActionResult Create()
  40.         {
  41.             return View();
  42.         }
  43.  
  44.         //
  45.         // POST: /Employee/Create
  46.  
  47.         [HttpPost]
  48.         public ActionResult Create(Employee employee)
  49.         {
  50.             if (ModelState.IsValid)
  51.             {
  52.                 db.Employees.Add(employee);
  53.                 db.SaveChanges();
  54.                 return RedirectToAction("Index");
  55.             }
  56.  
  57.             return View(employee);
  58.         }
  59.  
  60.         //
  61.         // GET: /Employee/Edit/5
  62.  
  63.         public ActionResult Edit(int id = 0)
  64.         {
  65.             Employee employee = db.Employees.Find(id);
  66.             if (employee == null)
  67.             {
  68.                 return HttpNotFound();
  69.             }
  70.             return View(employee);
  71.         }
  72.  
  73.         //
  74.         // POST: /Employee/Edit/5
  75.  
  76.         [HttpPost]
  77.         public ActionResult Edit(Employee employee)
  78.         {
  79.             if (ModelState.IsValid)
  80.             {
  81.                 db.Entry(employee).State = EntityState.Modified;
  82.                 db.SaveChanges();
  83.                 return RedirectToAction("Index");
  84.             }
  85.             return View(employee);
  86.         }
  87.  
  88.         //
  89.         // GET: /Employee/Delete/5
  90.  
  91.         public ActionResult Delete(int id = 0)
  92.         {
  93.             Employee employee = db.Employees.Find(id);
  94.             if (employee == null)
  95.             {
  96.                 return HttpNotFound();
  97.             }
  98.             return View(employee);
  99.         }
  100.  
  101.         //
  102.         // POST: /Employee/Delete/5
  103.  
  104.         [HttpPost, ActionName("Delete")]
  105.         public ActionResult DeleteConfirmed(int id)
  106.         {
  107.             Employee employee = db.Employees.Find(id);
  108.             db.Employees.Remove(employee);
  109.             db.SaveChanges();
  110.             return RedirectToAction("Index");
  111.         }
  112.  
  113.         protected override void Dispose(bool disposing)
  114.         {
  115.             db.Dispose();
  116.             base.Dispose(disposing);
  117.         }
  118.     }
  119. }

Views (Create,Details,Edit,Index ,Delete) and controlller(Employee) codes are automatically cretaed for CRUD operations.

Run the project

Manage/Index

Create

Edit

Details

Delete

The CRUD operations are working fine after using scaffolding. by this way we can save time while develop the application.

ModelBinding is the mechanism ASP.NET MVC uses to create strongly-typed objects (or fill primitive-type parameters) from the input stream (usually an HTTP request). The Model-Binder is then responsible to fill that person parameter for you.

Model Binding allows you to map and bind the HTTP request data with a model. If you want to work with the form data, Model Binding makes it easier because the requested data is submitted automatically into a data model that we specify. The Default Binder is used to do this. i explained the modelbinding with example,

Create New Project

created the project with name MvcModelBinding with basic template

Create the controller

created the new controller with name User

Create a new view

created the new view with name Userinfo under views->User Folder

Create a new model

code

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5.  
  6. namespace MvcModelBinding.Models
  7. {
  8.     public class UserInfoModel     {
  9.         public string Id { get; set; }
  10.         public string Name { get; set; }
  11.         public int Age { get; set; }
  12.         public string City { get; set; }
  13.         public string Country { get; set; }
  14.  
  15.     }
  16. }

created the new model with name UserInfoModel under model folder.it is having Name,Age,City and Country properties.

Add input fields into view

Code Snippet
  1. @{
  2.     ViewBag.Title = "UserInfo";
  3. }
  4. <h2>UserInfo</h2>
  5.     <div>
  6.             @{Html.BeginForm("UserInfo", "User");
  7.                 <table>
  8.                     <tr>
  9.                         <td>First Name : </td>
  10.                         <td>@Html.TextBox("fname")</td>
  11.                     </tr>
  12.                     <tr>
  13.                         <td>Middle Name : </td>
  14.                         <td>@Html.TextBox("midname")</td>
  15.                     </tr>
  16.                     <tr>
  17.                         <td>lastName :</td>
  18.                         <td> @Html.TextBox("lname")</td>
  19.                     </tr>
  20.                     <tr>
  21.                         <td>Age:</td>
  22.                         <td> @Html.TextBox("age") </td>
  23.                     </tr>
  24.  
  25.                      <tr>
  26.                         <td>Place:</td>
  27.                         <td> @Html.TextBox("place") </td>
  28.                     </tr>
  29.                      <tr>
  30.                         <td>Nationality:</td>
  31.                         <td> @Html.TextBox("nationality") </td>
  32.                     </tr>
  33.                     <tr>
  34.                         <td></td>
  35.                         <td>
  36.                             <input type="submit" name="Save" value="submit" />
  37.                         </td>
  38.                     </tr>
  39.                 </table>
  40.             }
  41.     </div>

created the textbox inputs for first name,middle name,last name,place,nationality and age in newly created view.

Create new UserModelBinding class for ModelBinding

Code Snippet
  1. using MvcModelBinding.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Http.Controllers;
  7. using System.Web.Http.ModelBinding;
  8. using System.Web.Mvc;
  9.  
  10. namespace MvcModelBinding.Data
  11. {
  12.     public class UserModelBinding : System.Web.Mvc.IModelBinder
  13.     {
  14.         public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
  15.         {
  16.             var request = controllerContext.HttpContext.Request;
  17.             var UserInfo = new UserInfoModel();
  18.             UserInfo.Name = string.Format("{0}{1}{2}", request.Form.Get("fname"), request.Form.Get("midname"), request.Form.Get("lname"));
  19.             UserInfo.Country = request.Form.Get("nationality");
  20.             UserInfo.City = request.Form.Get("place");
  21.             UserInfo.Age = Convert.ToInt32(request.Form.Get("age"));
  22.             return UserInfo;
  23.         }        
  24.     }
  25. }

created the new UserModelBinding class for model binding the inputs such as first name,middle name,last name,place,nationality and age from view.

Create action methods

Code Snippet
  1. public ActionResult UserInfo()
  2.         {
  3.             return View();
  4.         }
  5.         
  6.         [HttpPost]
  7.         public ActionResult UserInfo([ModelBinder(typeof(UserModelBinding))] UserInfoModel data)
  8.         {
  9.             // do database operations or any
  10.  
  11.             return View();
  12.         }

created two action methods for userinfo view and one defined as post with model binder used for convert the input values into UserInfoModel.

Modify the default action method

Code Snippet
  1. public static void RegisterRoutes(RouteCollection routes)
  2.         {
  3.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  4.  
  5.             routes.MapRoute(
  6.                 name: "Default",
  7.                 url: "{controller}/{action}/{id}",
  8.                 defaults: new { controller = "User", action = "UserInfo", id = UrlParameter.Optional }
  9.             );
  10.         }

modified the action and controller names for default in RouteConfig.cs file .

Run the project

just filled the informations for input fields

While debug the action method

The values are converted/assigned into UserInfoModel by ModelBinding

Application variable is available to all classes in an ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions.

Create application variable

Application["Message"] = "Welcome to the Contoso site.";

it shows how you can set the application variable Message to a string.

Application variable when the application starts

Application["Message"] = "Welcome to the site.";
Application["PageRequestCount"] = 0;

it shows how you can set the application variable Message to a string and initialize the variable PageRequestCount to 0.

Application variable with locking

Application.Lock();
Application["PageRequestCount"] = ((int)Application["PageRequestCount"])+1;
Application.UnLock();

it shows how you can lock and unlock application variable. The code increases the PageRequestCount variable by 1 and then unlocks application variable.

The MVC programming model is a lighter alternative to traditional ASP.NET (Web Forms). It is a lightweight, highly testable framework, integrated with all existing ASP.NET features, such as Master Pages, Security, and Authentication.

Create new Empty Project

in the above image, created new project with type of mvc 4.

Empty project template type with razor engine

Solution explorer with empty project template

we selected the empty project template while creating project so it is showing empty for controller section as well view section

Create new controller

Navigation for create

Controller name

After added

ViewBag used with controller

viewbag is used for transfer the values from controller to view. here, we used welcome for pass the welcome message.

Create new view

need create a folder

This folder name should be same as controller name.

Navigation for create

view name

After added

ViewBag used with view for display

This viewbag is passed from controller.

Update the default route

we need update the default controller and action names. because need update the newly created controller and action name.

In Browser


The datepicker is used to choose a date for input field.i just created sample page for jquery datepicker in aspx pages

Create a new project

This image shows the new project creation with name DatePicker

Create a new page

This image shows the new page creation with name DatePickerSamle

Add required files

We need add js (jquery-1.10.2.js,jquery-ui.js) and css(jquery-ui.css) files and these files are used for show datepicker.images folder added inside css folder

Call/Configure DatePicker Function

added textbox control txtdate and it is configured for datepicker.

DatePicker in Browser

DatePicker with previous/future dates only

In client side function

added textbox controls txtFutureDtae,txtPreviousDtae and it is configured for datepicker.

Previous days datepicker in Browser

Future days datepicker in Browser

DatePicker with sunday only

added textbox control txtSunday and it is configured for datepicker with allowed sunday only.

Sunday only datepicker in browser


A loop statement allows us to execute a statement or a group of statements multiple times and following is the general from of a loop statement in most of the programming languages.

The following loop types are available to handle looping requirements.

  • While loop
  • for loop
  • do while loop
  • Foreach loop

While loop

Description :
A while loop will check a condition and then continues to execute a block of code as long as the condition evaluates to a boolean value of true.

for loop

Description :
A for loop works like a while loop, except that the syntax of the for loop includes initialization and condition modification. for loops are appropriate when you know exactly how many times you want to perform the statements within the loop.

do while loop

Description :
A do loop is similar to the while loop, except that it checks its condition at the end of the loop. This means that the do loop is guaranteed to execute at least one time.

Foreach

Description :
A foreach loop is used to iterate through the items in a list. It operates on arrays or collections such as ArrayList, which can be found in the System.Collections namespace.

Powered by Blogger.