In This Article I will show you how to Bind Data to Webgrid in MVC. In this i will fetch data from database using Sql Query.And I Have a DropDown List if you selected any of value from list then webgrid shrink according to selected list value.
Before starting to read this article you must aware with
partial view in mvc (how to work thak and how to create).
So for this article first we will create our table to add....
Once table created in database enter some dummy data to test application now right click your project in solution explorer write the code like as shown below.
Add Model just like this and model name UserModel you can choose any name of model,as my previous article i have already told you how to add model in MVC application(right click on Model folder--->ADD---->Class and write the name of class UserModel)--->
write the code in UserModel like this..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication3.Models
{
public class UserModel
{
[Required(ErrorMessage = "Please Enter usre Name:")]
[Display(Name = "FirstName")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please Enter usre Name:")]
[Display(Name = "LastName")]
public string LastName { get; set; }
public string ddlJType { get; set; }
[Required(ErrorMessage = "Please Enter Email Address")]
[Display(Name = "Email")]
[RegularExpression(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$",
ErrorMessage = "Please Enter Correct Email Address")]
public string Email { get; set; }
[Required(ErrorMessage = "Please enter your Password")]
[StringLength(50, ErrorMessage = "Use 50 characters only.")]
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[System.Web.Mvc.Compare ("Password", ErrorMessage = "Password and confirm password must be same!")]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Please Enter Mobile No")]
[Display(Name = "Mobile")]
[StringLength(10, ErrorMessage = "The Mobile must contains 10 characters", MinimumLength = 10)]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered mobile format is not valid.")]
public string MobileNo { get; set; }
}
}
Step 2-
Make a separate folder for Connection for this right click on your application in solution explorer then Add then New Folder write the new folder name
Connection .
add a class class for Connection in Connection Folder.
you can add same as just like model.
Write the code in Connection Class like this--->
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
namespace MvcApplication3.Connection
{
public class Connection
{
public DataSet mydata()
{
SqlConnection con = new SqlConnection("Pass Your Connection String");
SqlCommand cmd = new SqlCommand("select * from regist", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
}
Step 3--->
Create a Controller you can choose any name of Controller and also working with HomeController.Write the code like in Controller.
public ActionResult Demo()
{
List<UserModel> rgst = new List<UserModel>();
DataSet ds = new DataSet();
Connection.Connection con = new Connection.Connection();
ds = con.mydata();
foreach (DataRow dr in ds.Tables[0].Rows)
{
rgst.Add(new UserModel
{
FirstName = dr["FirstName"].ToString(),
LastName = dr["LastName"].ToString(),
Email = dr["Email"].ToString(),
Password = dr["Pass"].ToString(),
MobileNo = dr["Mobile"].ToString()
});
}
return View(rgst);
}
Step 4-->
Create a view-->To Create on public ActionResult Demo() and then Add View...
Write the code like this in after Add View.
@model List<MvcApplication3.Models.UserModel>
@{
ViewBag.Title = "Demo";
var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 3,canSort:false);
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.edit-mode').hide();
$('.edit-user, .cancel-user').on('click', function () {
var tr = $(this).parents('tr:first');
tr.find('.edit-mode, .display-mode').toggle();
});
$('.save-user').on('click', function () {
var tr = $(this).parents('tr:first');
var fn = $(this).parents('tr').find("#FirstName").val();
var ln =$(this).parents('tr').find("#LastName").val();
var email =$(this).parents('tr').find("#Email").val();
var pass = $(this).parents('tr').find('#Password').val();
var mo =$(this).parents('tr').find("#MobileNo").val();
alert(fn+ln+email+pass+mo);
$.post("/User/InsertData",{FirstName:fn,LastName:ln,Email:email,Password:pass,Mobile:mo});
alert("ok");
location.reload();
});
$('.delete-user').on('click', function () {
var fn = $(this).parents('tr').find("#FirstName").val();
var ln =$(this).parents('tr').find("#LastName").val();
var email =$(this).parents('tr').find("#Email").val();
var pass = $(this).parents('tr').find('#Password').val();
var mo =$(this).parents('tr').find("#MobileNo").val();
alert(fn+ln+email+pass+mo);
$.post("/User/DeleteData",{FirstName:fn,LastName:ln,Email:email,Password:pass,Mobile:mo});
alert("Are You Sure To Delete Data:" +email);
location.reload();
});
})
</script>
<style type="text/css">
.table
{
margin: 8px;
border-collapse: collapse;
width: 300px;
}
.header
{
background-color: green;
font-weight: bold;
color: #fff;
}
.table th, .table td
{
border: 2px solid black;
padding: 10px;
}
</style>
<div id="gridContent">
@grid.GetHtml(
tableStyle: "table",
fillEmptyRows: true,
headerStyle: "header",
alternatingRowStyle: "alt",
footerStyle: "grid-footer",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new[]
{
grid.Column("FirstName", "First Name",format: @<text><label id="lblFirstName" >@item.FirstName</label> <input type="text" id="FirstName" value="@item.FirstName" class="edit-mode" ,readonly = "true" /></text>, style: "col1Width"),
grid.Column("LastName", "Last Name", format: @<text> <label id="lblLastName" >@item.LastName</label> <input type="text" id="LastName" value="@item.LastName" class="edit-mode" /></text>, style: "col1Width"),
grid.Column("Email", "Email", format: @<text> <label id="lblEmail" >@item.Email</label> <input type="text" id="Email" value="@item.Email" class="edit-mode" /></text>, style: "col1Width"),
grid.Column("Password", "Password", format: @<text> <label id="lblPassword" >@item.Password</label> <input type="text" id="Password" value="@item.Password" class="edit-mode" /></text>, style: "col1Width"),
grid.Column("Mobile", "Mobile Number", format: @<text> <label id="lblMobileNo" >@item.MobileNo</label> <input type="text" id="MobileNo" value="@item.MobileNo" class="edit-mode" /></text>, style: "col1Width"),
grid.Column("Action", format: @<text> <button class="edit-user display-mode" >Edit</button>
<button class="save-user edit-mode" >Save</button>
<button class="cancel-user edit-mode" >Cancel</button>
<button class="delete-user edit-mode" >Delete</button>
</text>, style: "col3Width" , canSort: false)
})
Run The project it will show you the output as follows-->
It will show you in Paging format if you are not interested in paging then, In view you can remove the following
canPage: true, rowsPerPage: 3 OR you do change
canPage: false, rowsPerPage: 3 .