MVC 4 sample Webgrid Application With JQuery Ajax
1. Introduction
MVC is not a new concept made for ASP.NET. Even iOS framework is based on MVC for its development.
MVC is a general concept of Software Engineering.
The central idea behind MVC is separation of concerns and code reusability. Views do not need to know where the data come from. Models also do not know anything about how the data will be displayed. By doing so, you can have very flexible architecture that can be changed and maintained easily.
This booklet explains the followings:
MVC Overview
Controllers
Views (WebForms and Razor)
Models and Validations
Filters
Unobtrusive Ajax
Dependency Injection (DI) Pattern
The following tools are used for the project:
Visual Studio Express 2012 for Web
SQL Server 2012 Express
2. ASP.NET MVC
Ok, everybody talks about MVC and you know what MVC stands for.
M (Model): Data objects – business logic, validation, and DB access
V (View) : UI
C (Controller): well, it does many things; handles user interaction, works with models, and selects a view, etc.
In this chapter, we look at how MVC handles a request (execution process) first. It will give you the high level view of what MVC is. And then let’s find out how MVC project looks like from the developer’s point of view.
so lets start with a sample application here i have provided sample codes for controller,Models and views
controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using projectManagement.Models;
namespace projectManagement.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
List<Projects> emp=new List<Projects>()
{
new Projects () { ID=100,projectName="Geojith",employeeName="Jithin"},
new Projects () { ID=101,projectName="CateringManagement",employeeName="Jerin"},
};
public ActionResult Index()
{
List<Projects> emplist = new List<Projects>();
return View(emp);
}
public ActionResult update()
{
string message = "Success";
return Json(message, JsonRequestBehavior.AllowGet);
}
public ActionResult updatebyajax()
{
return View(emp);
}
[HttpPost]
public ActionResult Insert(Projects pro)
{
emp.Add(pro);
//return this.Json(new { msg = "success" });
return View("updatebyajax", emp);
}
}
}
Views
Home/updatebyajax
@model List<projectManagement.Models.Projects>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="../../Content/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
$('.edit').hide();
$('.Insert').hide(); //hiding three buttons initially
$('.edit-user, .cancel-user').on('click', function () {//common for both editing and cancel ...while cliccking
var tr = $(this).parents('tr:first'); //it will find the parent table row in which click has occured
tr.find('.edit, .view').toggle(); //and toggle corresponding edit or view controls
});
$('.save-user').on('click', function () {//on clicking save button
var tr = $(this).parents('tr:first');
var FirstName = tr.find("#projectName").val(); ///
var LastName = tr.find("#employeeName").val();
var UserID = tr.find("#UserID").html();
tr.find("#lblprojectName").text(FirstName);
tr.find("#lblemployeeName").text(LastName);
tr.find('.edit, .view').toggle();
var UserModel =
{
"ID": UserID,
"FirstName": FirstName,
"LastName": LastName
};
$.ajax({
url: '/Home/update/',
data: JSON.stringify(UserModel),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
$('.delete-user').on('click', function () {//on clicking save button
alert("Do you Really want to Delete This ?")
var tr = $(this).parents('tr:first');
$(this).closest('tr').remove();
});
$('.insert-user').on('click', function () {
$('.insert-user').hide();
$('p').append('<table>' + '<tr>' + '<td><input type="text" id="UserIDInsert" class="insert" />' +
'<td><input type="text" id="projectNameInsert" class="insert" />' +
'<td><input type="text" id="employeeNameInsert" class="insert" />' + '<td><input type="submit" id="submit" class="insert" /></td>' + '</tr>' + '</table>');
$('#submit').on('click', function () {
var tr = $(this).parents('tr:first');
var projectName = tr.find("#projectNameInsert").val();
var employeeName = tr.find("#employeeNameInsert").val();
var UserID = tr.find("#UserIDInsert").val();
var UserModel =
{
"ID": UserID,
"projectName": projectName,
"employeeName": employeeName
};
$('.insert').hide();
$.ajax({
url: '/Home/Insert/',
data: JSON.stringify(UserModel),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function () {
alert("Value Inserted");
}
});
})
});
})
</script>
<h2>Student</h2>
@{
var grid = new WebGrid(source:Model);
}
<h2>updatebyajax</h2>
<div id="gridContent" style=" padding:20px; " >
@grid.GetHtml(
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
columns:
grid.Columns(
grid.Column("ID", format: @<text> <span class="view">@item.ID </span> <label id="UserID" class="edit">@item.ID</label> </text>, style: "col1Width" ),
grid.Column("projectName", "Project Name", format: @<text> <span class="view"> <label id="lblprojectName" >@item.projectName</label> </span> <input type="text" id="projectName" value="@item.projectName" class="edit" /> </text>, style: "col2Width"),
grid.Column("employeeName", "Employee Name", format: @<text> <span class="view"> <label id="lblemployeeName">@item.employeeName</label> </span> <input type="text" id="employeeName" value="@item.employeeName" class="edit" /> </text>, style: "col2Width"),
grid.Column("Action", format: @<text>
<button class="edit-user view" >Edit</button>
<button class="delete-user view" >Delete</button>
<button class="save-user edit" >Save</button>
<button class="cancel-user edit" >Cancel</button>
</text>, style: "col3Width" , canSort: false)))
<button class="insert-user" >Insert New</button>
<p> </p>
</div>
Models
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace projectManagement.Models
{
public class Projects
{
[Key]
public int ID { get; set; }
public string projectName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime startdate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime endDate { get; set; }
public string employeeName { get; set; }
[RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$",
ErrorMessage = "Invalid email address.")]
public string Email { get; set; }
}
}
1. Introduction
MVC is not a new concept made for ASP.NET. Even iOS framework is based on MVC for its development.
MVC is a general concept of Software Engineering.
The central idea behind MVC is separation of concerns and code reusability. Views do not need to know where the data come from. Models also do not know anything about how the data will be displayed. By doing so, you can have very flexible architecture that can be changed and maintained easily.
This booklet explains the followings:
MVC Overview
Controllers
Views (WebForms and Razor)
Models and Validations
Filters
Unobtrusive Ajax
Dependency Injection (DI) Pattern
The following tools are used for the project:
Visual Studio Express 2012 for Web
SQL Server 2012 Express
2. ASP.NET MVC
Ok, everybody talks about MVC and you know what MVC stands for.
M (Model): Data objects – business logic, validation, and DB access
V (View) : UI
C (Controller): well, it does many things; handles user interaction, works with models, and selects a view, etc.
In this chapter, we look at how MVC handles a request (execution process) first. It will give you the high level view of what MVC is. And then let’s find out how MVC project looks like from the developer’s point of view.
so lets start with a sample application here i have provided sample codes for controller,Models and views
controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using projectManagement.Models;
namespace projectManagement.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
List<Projects> emp=new List<Projects>()
{
new Projects () { ID=100,projectName="Geojith",employeeName="Jithin"},
new Projects () { ID=101,projectName="CateringManagement",employeeName="Jerin"},
};
public ActionResult Index()
{
List<Projects> emplist = new List<Projects>();
return View(emp);
}
public ActionResult update()
{
string message = "Success";
return Json(message, JsonRequestBehavior.AllowGet);
}
public ActionResult updatebyajax()
{
return View(emp);
}
[HttpPost]
public ActionResult Insert(Projects pro)
{
emp.Add(pro);
//return this.Json(new { msg = "success" });
return View("updatebyajax", emp);
}
}
}
Views
Home/updatebyajax
@model List<projectManagement.Models.Projects>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="../../Content/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
$('.edit').hide();
$('.Insert').hide(); //hiding three buttons initially
$('.edit-user, .cancel-user').on('click', function () {//common for both editing and cancel ...while cliccking
var tr = $(this).parents('tr:first'); //it will find the parent table row in which click has occured
tr.find('.edit, .view').toggle(); //and toggle corresponding edit or view controls
});
$('.save-user').on('click', function () {//on clicking save button
var tr = $(this).parents('tr:first');
var FirstName = tr.find("#projectName").val(); ///
var LastName = tr.find("#employeeName").val();
var UserID = tr.find("#UserID").html();
tr.find("#lblprojectName").text(FirstName);
tr.find("#lblemployeeName").text(LastName);
tr.find('.edit, .view').toggle();
var UserModel =
{
"ID": UserID,
"FirstName": FirstName,
"LastName": LastName
};
$.ajax({
url: '/Home/update/',
data: JSON.stringify(UserModel),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
$('.delete-user').on('click', function () {//on clicking save button
alert("Do you Really want to Delete This ?")
var tr = $(this).parents('tr:first');
$(this).closest('tr').remove();
});
$('.insert-user').on('click', function () {
$('.insert-user').hide();
$('p').append('<table>' + '<tr>' + '<td><input type="text" id="UserIDInsert" class="insert" />' +
'<td><input type="text" id="projectNameInsert" class="insert" />' +
'<td><input type="text" id="employeeNameInsert" class="insert" />' + '<td><input type="submit" id="submit" class="insert" /></td>' + '</tr>' + '</table>');
$('#submit').on('click', function () {
var tr = $(this).parents('tr:first');
var projectName = tr.find("#projectNameInsert").val();
var employeeName = tr.find("#employeeNameInsert").val();
var UserID = tr.find("#UserIDInsert").val();
var UserModel =
{
"ID": UserID,
"projectName": projectName,
"employeeName": employeeName
};
$('.insert').hide();
$.ajax({
url: '/Home/Insert/',
data: JSON.stringify(UserModel),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function () {
alert("Value Inserted");
}
});
})
});
})
</script>
<h2>Student</h2>
@{
var grid = new WebGrid(source:Model);
}
<h2>updatebyajax</h2>
<div id="gridContent" style=" padding:20px; " >
@grid.GetHtml(
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
columns:
grid.Columns(
grid.Column("ID", format: @<text> <span class="view">@item.ID </span> <label id="UserID" class="edit">@item.ID</label> </text>, style: "col1Width" ),
grid.Column("projectName", "Project Name", format: @<text> <span class="view"> <label id="lblprojectName" >@item.projectName</label> </span> <input type="text" id="projectName" value="@item.projectName" class="edit" /> </text>, style: "col2Width"),
grid.Column("employeeName", "Employee Name", format: @<text> <span class="view"> <label id="lblemployeeName">@item.employeeName</label> </span> <input type="text" id="employeeName" value="@item.employeeName" class="edit" /> </text>, style: "col2Width"),
grid.Column("Action", format: @<text>
<button class="edit-user view" >Edit</button>
<button class="delete-user view" >Delete</button>
<button class="save-user edit" >Save</button>
<button class="cancel-user edit" >Cancel</button>
</text>, style: "col3Width" , canSort: false)))
<button class="insert-user" >Insert New</button>
<p> </p>
</div>
Models
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace projectManagement.Models
{
public class Projects
{
[Key]
public int ID { get; set; }
public string projectName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime startdate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime endDate { get; set; }
public string employeeName { get; set; }
[RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$",
ErrorMessage = "Invalid email address.")]
public string Email { get; set; }
}
}
Comments
Post a Comment