Filter Gridview Using Ajax Scroll


Introduction

This is very simple example of use Ajax Slide Control to filter data in a grid view.  Sometimes we need to filter the gridview data based on some range value. On that case we can use AJAX Slider control to provide scrollable Filter functionality with gridview control.

To discuss about the implementation,  lets break down the project into three part

  1. Data Source
  2. ASPX Page
  3. Use of Codebehind

 

Data Source

Data source is used to bind the data with grid view.  It may be an XML, or Data Set or From Database. In this example I have used XML as data source.  Which loads as a dataset to bind with grid view.  Below is the structure of the XML File that I have used for this application.

<students>

  <student>

    <roll>1</roll>

    <name>A</name>

    <address>Kolkata</address>

    <marks>88</marks>

  </student>

  <student>

    <roll>2</roll>

    <name>B</name>

    <address>Pune</address>

    <marks>77</marks>

  </student>

     .

     .

     .

</students>

we can use some different data source also like  Database or anything else as per the requirements.

ASPX Page Implementation

In the aspx page we have used on Update Panel that contain the gridview. Data source of the gridview has been defined from Codebehind code as Data going to be chage while filtering. We have also used one AJAX Slider control to filter the data on slider change.

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">

            <ContentTemplate>

                <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"

                    Width="222px">

                    <RowStyle BackColor="#EFF3FB" />

                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

                    <EditRowStyle BackColor="#2461BF" />

                    <AlternatingRowStyle BackColor="White" />

                </asp:GridView>

            </ContentTemplate>

        </asp:UpdatePanel>

    </div>

    <cc1:SliderExtender ID="SliderExtender1" runat="server" BoundControlID="lbl"

        Decimals="0" Minimum="1" Maximum="9"  TargetControlID="TextBox1"

        EnableHandleAnimation="true" TooltipText="{0}">

    </cc1:SliderExtender>


    <p>

        <asp:TextBox ID="TextBox1" AutoPostBack="true"
runat="server"
OnTextChanged="txtSlider_TextChanged"></asp:TextBox>

        <asp:Label ID="lbl"></asp:Label>

    </p>

We have one textBox that sets as TargetControlID of SilderControl. So, what ever the value will change in Slider will reflect in textbox and whenever we have change value in textbox, txtSlider_TextChanged event will fire which will do the filter from codebehind.

Lets have a look what we have to do in Server side code.

Use of Codebehind

During the page load, first we need to load all the data from XML File, like below

protected void Page_Load(object sender, EventArgs e)
    {
       //Check For Post back or not
        if (!Page.IsPostBack)
        {
           Ds.ReadXml(Server.MapPath("Result.xml"));
           GridView1.DataSource = Ds;
           GridView1.DataBind();
        }
    }

This will load all the data form XML To Gridview.

Now, lets have look into the txtSlider_TextChanged which will call automatically on slider change.

protected void txtSlider_TextChanged(object sender, EventArgs e)
    {
        // Filter based on Rool
        string query = "roll >= " + TextBox1.Text;
        Ds.ReadXml(Server.MapPath("Result.xml"));
        DataTable dt1 = Ds.Tables[0];
        //Apply Select Query
        var v =dt1.Select(query);
        DataTable dt = new DataTable("Customers");
        // Add columns in DataTable
        dt.Columns.Add("Roll", typeof(string));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        dt.Columns.Add("Marks", typeof(string));
        foreach (DataRow dRow in v)
        {
           DataRow dr = dt.NewRow();
            dr["Roll"] = dRow["roll"];
            dr["Name"] = dRow["name"];
            dr["Address"] = dRow["address"];
           dr["Marks"] = dRow["marks"];
            dt.Rows.Add(dr);
        }
        GridView1.DataSource = dt;
            GridView1.DataBind();
    }

Some Filtered Records

Here you can check we have filter the data based on Roll Number.

        string query = "roll >= " + TextBox1.Text;
        var v =dt1.Select(query);

You can change the condition of filter as per your requirement.

Conclusion

This is a very simple article which shows you how to use Slider Control to Filter Data in GridView. You can use any data source like database or XML for the same. Please feel free to download the sample from above and use it wherever you like. I will write one more article on how to filter data using AJAX MultiSlider soon.  Please provide your valuable suggestion and feedback.

How to Freeze GridView Header While Scrolling ?


 This is very common problem in Web development that we need to freeze the GridView header at the time of scrolling, Here is one simple tips:

Step 1 : Create a CSS class as following

.HeaderFreez
{
position:relative ;
top:expression(this.offsetParent.scrollTop);
z-index: 10
}

Step 2 Set Gridview’s HeaderStyle CssClass as follows

CssClass="HeaderFreez" 

Using a Webgrid that can sort, page, and filter in Asp.Net MVC3


Getting the MvcWebGrid app setup

To begin, create a new MVC3 application called MvcWebGrid.  Make sure you select Empty for the template, and that the view engine is set to Razor.  Next, right click on the Controllers folder and select add->New Controller.  Name the controller HomeControler, and leave the checkbox to create the CRUD methods unchecked.

For simplicity sake, we will not connect to a real database in this sample.  Instead, I have created a class that returns a lists of music albums (generated from the MvcMusicStore tutorial at mvcmusicstore.codeplex.com).  You can find this class in the code download (linked at the end of this article), or here on github.  This is a simple static class with a single method called GetAlbums, which returns an IEnumerable<Album>.  Add this class to your models folder.

In your home controller, modify your Index action method to like like so:

  public ActionResult Index()
        {
            var obj = new AlbumRepo();
            var albums = obj.GetAlbums();
            return View(albums);
        }

In _LayouPage write down below given code
 <div id="header">
        Welcome to my awesome music site where a deep dish of awesome stew is served up
        daily
        <p />
        <p />
        <p />
        <ul>
            <li>@Html.ActionLink("Index", "Index", "Grid")</li>
            <li>@Html.ActionLink("Ajax2", "IndexWithAjax","Grid",new { ajax = "this is ajax sample" },null)</li>
        </ul>
    </div>
    @RenderBody()
    <div id="footer">
        <p />
        You have reached the bottom of this page, now what?
    </div>

Adding the WebGrid to the app

Now that we have a basic layout for our site, lets create the index view.  Go back to the home controller, right click anywhere within the index action method, and select add view.  Keep all the defaults and click Add.

Change the new view to look like the following:

   1:  @model IEnumerable<Album>
   2:   
   3:  @{
   4:      ViewBag.Title = "MVC Music Store Grid";
   5:  }
   6:   
   7:  @using (Html.BeginForm())
   8:  {
   9:      <fieldset>
  10:          <legend>Search</legend>
  11:   
  12:          <div>
  13:              Album Id:
  14:          </div>
  15:          <div>
  16:              <input type="text" id="albumid" name="albumid" />
  17:          </div>
  18:   
  19:          <div>
  20:              Album Name:
  21:          </div>
  22:          <div>
  23:              <input type="text" id="albumName" name="albumName" />
  24:          </div>
  25:   
  26:          <p>
  27:              <input type="submit" value="Search" />
  28:          </p>
  29:      </fieldset>
  30:  }
  31:   
  32:  <div id="myGrid">
  33:      @Html.Partial("_grid", Model)
  34:  </div>

We will be separating the WebGrid into its own partial view, so right click on the Views/Home folder, select add, and then view.  Name the view _grid, and check the “Create as a partial view” checkbox, then click add.  Prepending the name of our Razor view with a underscore tells Asp.Net that this file should not be served if requested directly, which is perfect for our partial views.

In our grid partial view, we will now be using the new WebGrid helper.  We start off creating an instance of the WebGrid (passing in our model into the constructor), and then call the GetHtml method which generates the html for the grid and outputs it to the screen:

   1:  @model IEnumerable<Album>
   2:   
   3:  @{
   4:      var grid = new WebGrid(Model);
   5:      @grid.GetHtml();
   6:  }

When we run the app, we get a web page that looks like so:

image

If you inspect the html for the new grid, you will see that it is clean markup, with no added styles or nasty viewstate that we have seen in the past with WebForms.  You might also notice that the table html is semantically correct, where the header is in the thead section, the content in the tbody section, and the paging in the tfoot section.  Having your tables formatted properly will go a long ways if you want to try to extend your table functionality using JavaScript libraries such as jQuery, where it was often difficult to achieve this in WebForms.

Another bonus is that the paging and sorting already work!  Out of the box, the WebGrid provides these functions by doing Get requests and passing in a few values over the query string.  The WebGrid will see these values in the new request, and adjust the output accordingly.  This means that the WebGrid expects the entire set of data in each view in order to generate the paging properly.  For small sets of data this is not a problem, but even in our sample app you can notice a lag when hitting the links.  Fixing this issue is out of the scope of this article, but just be aware that you will need to come up with a different solution if your data sets are large.

The WebGrid provides a lot of options for configuration.  These options are provided by passing in parameters to the WebGrid’s constructor, as well as the GetHtml method.

image

image

We will modify some of these options to add some Ajax functionality to the screen (so that paging and sorting don’t refresh the entire screen), as well as change how some of the columns appear.  Modify _grid.cshtml to look like so:

   1:  @model IEnumerable<Album>
   2:   
   3:  @{
   4:      var grid = new WebGrid(Model, rowsPerPage: 15, ajaxUpdateContainerId: "myGrid");
   5:      @grid.GetHtml(columns: grid.Columns(
   6:                          grid.Column("AlbumId", "Album Id"),
   7:                          grid.Column("Title", "Title"),
   8:                          grid.Column("Artist", "Artist")
   9:                          ));
  10:  }

In the constructor, we setting the size of the page to handle 15 albums at a time, as well as setting the container id of the div in the index.cshtml page that holds our grid.  The simple act of setting the ajaxUpdateContainerId will automatically enable our screen to use Ajax to update the screen on pages and sorts.  All we need to do is make sure jQuery is included in the project, which it is by default in the _Layout.cshtml page.

The GetHtml method take a columns param, where we pass in a list of column objects we want to use on the grid.

One thing I don’t particularly care for is how the Ajax is inserted into the page.  If you take a look at the source, all of the links now have onclick methods inserted into them.  This gets away from the unobtrusive JavaScript theme the rest of MVC3 strived so hard to achieve.  We will talk some more about unobtrusive JavaScript in the next section.

Filtering the grid

You probably noticed that our index.cshtml page has had a form in it that we will be using to filter the data in the grid.  This form is simple by design, and will allow us to filter the form either by the Album Id, or the Album Name.  Before we do anything with the form, lets add a new action method in our home controller that will let us filter the data:

   1:  [HttpPost]
   2:  public ActionResult Index(int? albumId, string albumName)
   3:  {
   4:      var albums = AlbumRepo.GetAlbums();
   5:   
   6:      if (!string.IsNullOrEmpty(albumName))
   7:          albums = albums.Where(a => a.Title.Contains(albumName)).ToList();
   8:   
   9:      if (albumId.HasValue)
  10:          albums = albums.Where(a => a.AlbumId == albumId).ToList();
  11:   
  12:      return View(albums);
  13:  }
 
This new action method has the same name as our other action method, but has the HttpPost attribute which tells MVC that this method will only respond to post requests.  We accept two params into the method that will be used to filter the data. (Note: the code in this action method is not a good way to filter data, it is just demo code, so don’t reuse it in production).
Now when we run the app, we can filter the data.  However, our site is doing a complete post and refresh of the page every time we do a search.  We will now add Ajax to the form.
We will use the new unobtrusive Ajax support that is in MVC3 to accomplish this, and do it without having to write a single line of JavaScript.  The Ajax.BeginForm has been around for awhile in MVC, but it has been changed to now use jQuery and not the Microsoft Ajax library.  Also, there is no more JavaScript inserted into the screen on your behalf (unlike the WebGrid Ajax support shown above).  Instead, MVC3 uses HTML5 data attributes to mark the form, and a special script that is used to wire the Ajax functionality up at runtime.
In index.cshtml, change the Html.BeginForm line to the following:
   1:  @using (Ajax.BeginForm(new AjaxOptions 
   2:      { InsertionMode = InsertionMode.Replace, UpdateTargetId = "myGrid" }))
   3:  {
The AjaxOptions parameter tells our form how to handle the Ajax reqeuest.  In this case, we are telling it we want the InsertionMode to replace the current contents in the myGrid div tag (much like we did with the paging and sorting on the grid).  All that is left to do is add the JavaScript file that will make this magic happen.  In the _Layout.cshtml file, add the following line directly below the line that includes jQuery:
   1:  <script type="text/javascript" src="../../Scripts/jquery.unobtrusive-ajax.min.js">
   2:  </script>  

Make sure you don’t include any of the JavaScript files that start with Microsoft, as those are just included for backwards compatibility.  In MVC3, you want to be using the scripts who’s filenames start with jQuery.

If you run the app now, you might notice a strange oddity when filtering the data.  The entire response is copied into the myDiv tag, meaning that we get another copy of the form, along with the WebGrid table again.  When using Ajax.BeginForm, the response that is sent is expected to only be the content that changes, not the entire page.  We can easily fix this and return just the updated grid by changing the index action method that accepts the HttpPost to return a partial view of only the grid and not the entire index view (this is why we separated the grid out from the index view in the first place).

Update the index action method for the filtering to return a partial view by modifying the last line as such:

   1:  return PartialView("_grid", albums);

Now when you enter an a AlbumId or a partial Album name, the grid will filter and display properly.

Download Source Code : https://docs.google.com/file/d/0B-sDsBkcsM1YVUJwSUN0YWJFTU0/edit?usp=sharing

DropDownList in GridView Async and find Control in Class File in c#.net


In this article, I have described the ways of keeping DropDownList in the GridView and binding the data by preserving the default SelectedValue. Apart from DropDownList, I have also shown how to keep CheckBox, RadioButtonList, TextBox in the GridView and preserving the default data,how to find control in class file ,how to use async Trigger in Update Panel using GridView in C#.net

Placing the DropDownList in the GridView

To place the DropDownList in the GridView, you will have to use asp:TemplateField that under <Columns>, Generally you will need to use the DropDownList in the GridView in the Edit mode (under EditItemTemplate, However this solution will work for you even if you want to place the DropDownList in the ItemTemplate) where you want your user to select the data from the DropDownList and update the record. A typical example is shown in the picture below

Image

The aspx page code of above GridView is below

<%@ Page Title="" Language="C#" MasterPageFile="~/GridMaster.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="Default" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"
    ClientIDMode="Static">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" ClientIDMode="Static">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="GridView1" />
        </Triggers>
        <ContentTemplate>
            <asp:Label ID="lblMessage" runat="server" EnableViewState="true" />
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ClientIDMode="Static"
                GridLines="None" AutoGenerateEditButton="True" OnRowCancelingEdit="GridViewCancelEdit"
                OnRowEditing="GridViewEdit" OnRowUpdating="GridViewUpdate" 
                DataKeyNames="PersonID" CellPadding="4" ForeColor="#333333">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:BoundField DataField="PersonID" HeaderText="Person ID" ReadOnly="True" Visible="false" />
                    <asp:TemplateField HeaderText="First Name">
                        <ItemTemplate>
                            <%# Eval("FName") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FName") %>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Last Name">
                        <ItemTemplate>
                            <%# Eval("LName") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LName") %>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Department DropDown">
                        <ItemTemplate>
                            <%# Eval("DeptName")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:DropDownList ID="dropDownDept" DataSource="<%# BindDropDownDepartment() %>"
                                DataTextField="DeptName" DataValueField="DeptId" runat="server" SelectedValue='<%# Eval("DeptId").ToString() %>'>
                            </asp:DropDownList>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="CustomCheckBox Field">
                        <ItemTemplate>
                            <%# Eval("IsActive") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:CheckBox ID="chkActive" runat="server" Checked='<%# Eval("IsActive") %>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="RadioButtonField">
                        <ItemTemplate>
                            <%# Eval("IsActive") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:RadioButtonList ID="radioActive" runat="server" RepeatDirection="Horizontal"
                                RepeatLayout="Flow" SelectedValue='<%# Eval("IsActive") %>'>
                                <asp:ListItem Text="True" Value="True" />
                                <asp:ListItem Text="False" Value="False" />
                            </asp:RadioButtonList>
                        </EditItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

In your code behind file of Default.aspx.cs code will be such as below given

using System;
using System.Data;
 
public partial class Default : System.Web.UI.Page
{
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var obj = new BAL();
            obj.LoadPerson(ref  GridView1);
        }
    }
    
    protected DataTable BindDropDownDepartment()
    {
        var obj = new BAL();
        return obj.LoadAll();
    }
    protected void GridViewCancelEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
    {
        var obj = new BAL();
        GridView1.EditIndex =-1;
        obj.LoadPerson(ref  GridView1);
 
    }
    protected void GridViewEdit(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
    {
        var obj = new BAL();
        GridView1.EditIndex = e.NewEditIndex;
        obj.LoadPerson(ref  GridView1);
 
    }
    protected void GridViewUpdate(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
    {
        
        GridView1.EditIndex = -1;
        var obj = new BAL();
        obj.UpdateGrid(ref GridView1, e.RowIndex);
    }
}

Now Add a class File in Your Application and write down in that below given code.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
 
/// <summary>
/// Summary description for BAL
/// </summary>
public class BAL
{
 
    public BAL()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public void LoadPerson(ref GridView grd)
    {
 
        using (var objCon = new SqlConnection())
        {
            objCon.ConnectionString = ConfigurationManager.ConnectionStrings["cnGrid"].ConnectionString;
            if (objCon.State == ConnectionState.Closed)
                objCon.Open();
            using (var objAdp = new SqlDataAdapter("usp_PersonRecords", objCon))
            {
                objAdp.SelectCommand.CommandType = CommandType.StoredProcedure;
                var ds = new DataSet();
                objAdp.Fill(ds);
                grd.DataSource = ds.Tables[0];
                grd.DataBind();
            }
        }
 
    }
    public DataTable LoadAll()
    {
        dynamic objDt;
        using (var objCon = new SqlConnection())
        {
            objCon.ConnectionString = ConfigurationManager.ConnectionStrings["cnGrid"].ConnectionString;
            if (objCon.State == ConnectionState.Closed)
                objCon.Open();
            using (var objAdp = new SqlDataAdapter("usp_DeptRecords", objCon))
            {
                objAdp.SelectCommand.CommandType = CommandType.StoredProcedure;
                var ds = new DataSet();
                objAdp.Fill(ds);
                objDt = ds.Tables[0];
            }
        }
        return objDt;
    }
    public void UpdateGrid(ref GridView grd, int index)
    {
 
        var row = grd.Rows[index];
        var ddlDept = (DropDownList)row.FindControl("dropDownDept");
        var txtFname = (TextBox)row.FindControl("txtFirstName");
        var txtLname = (TextBox)row.FindControl("txtLastName");
        var isActive = (RadioButtonList)row.FindControl("radioActive");
        var chkAct = (CheckBox)row.FindControl("chkActive");
 
        var id = Convert.ToInt32(grd.DataKeys[row.RowIndex].Value);
        var FNAME = txtFname.Text.ToUpper();
        var lname = txtLname.Text.ToUpper();
        var deptID = Convert.ToInt32(ddlDept.SelectedItem.Value);
        var isactive = isActive.SelectedValue == "True" ? Convert.ToInt32(1) : Convert.ToInt32(0);
        using (var objCon = new SqlConnection())
        {
            objCon.ConnectionString = ConfigurationManager.ConnectionStrings["cnGrid"].ConnectionString;
            if (objCon.State == ConnectionState.Closed)
                objCon.Open();
            using (var cmd = new SqlCommand("usp_PersonUpdate", objCon))
            {
                cmd.CommandType = CommandType.StoredProcedure;
 
                var parm = new[]
                               {
                                   new SqlParameter("@PersonID", SqlDbType.Int, Int32.MaxValue) {Value =id},
                                   new SqlParameter("@FName", SqlDbType.VarChar, 100) {Value =FNAME },
                                   new SqlParameter("@LName", SqlDbType.VarChar, 100) {Value = lname},
                                   new SqlParameter("@DeptID", SqlDbType.Int, Int32.MaxValue) {Value =deptID},
                                   new SqlParameter("@IsActive", SqlDbType.Bit) {  Value = isactive}
                               };
                cmd.Parameters.AddRange(parm);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                LoadPerson(ref grd);
            }
        }
    }
}

Now  Run by pressing F5 remember that before run to this ensure your database and connection string  in web config file and change in that setting of your MSSQLServer

<connectionStrings>
		<add name="cnGrid" connectionString="Data Source=xxxx;Initial Catalog=dbGrid;Persist Security Info=True;User ID=xxx;Password=xxx;Pooling=False" providerName="System.Data.SqlClient"/>
</connectionStrings>

Download Url : https://docs.google.com/file/d/0B-sDsBkcsM1YODBWaVZmLTJ6YlE/edit?usp=sharing

Differences between viewdata, viewbag and tempdata in mvc3


Differences between viewdata, viewbag and tempdata in mvc3

 

In Asp.net MVC, we have three objects – ViewData, ViewBag and TempData to pass data from controller to view and in next request.

ViewData

1.ViewData is a dictionary object that is derived from ViewDataDictionary class.

2.ViewData is used to pass data from controller to corresponding view.

3.It’s life lies only during the current request.

4.If redirection occurs then it’s value becomes null.

5.It’s required typecasting for complex data type and check for null values to avoid error.

ViewBag

1.ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.

2.Basically it is a wrapper around the ViewData and also used to pass data from controller to      corresponding view.

3.It’s life also lies only during the current request.

4.If redirection occurs then it’s value becomes null.

5.It doesn’t required typecasting for complex data type.

TempData

1.TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.

2.TempData is used to pass data from current request to subsequent request means incase of redirection.

3.It’s life is very short and lies only till the target view is fully loaded.

4.It’s required typecasting for complex data type and check for null values to avoid error.

5.It is used to store only one time messages like error messages, validation messages.

ViewData, ViewBag and TempData Current Request Example

public class HomeController : Controller
{
public ActionResult Index()
{
var cust= new Customer
{
CustID=101,
Name = "Rajesh",

};
ViewData["cust"] = cust;
ViewBag.Customer = cust;
TempData["cust"] = cust;
return View();
}
}

return View(); }
}
@model MvcSample.Models.CustomerModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Welcome to MVC Tutorails";
var viewDataCustomer = ViewData["cust"] as Customer; //need typcasting
var tempDataCustomer = TempData["cust"] as Customer; //need typcasting
}
<h2>Welcome to MVC Tutorials</h2>
This Best behavioral customer is!
<h4>@ViewBag.cust.Name</h4>
<h3>@viewDataCustomer.Name</h3>
<h2>@tempDataCustomer.Name</h2>
</div>

ViewData, ViewBag and TempData Next Request Example

public ActionResult About()
{
var cust= new Customer {
CustID=007,
Name = "Rajesh",
};
ViewData["cust"] = cust;
ViewBag.Customer = cust;
TempData["cust"] = cust;
//After the redirection, ViewData and ViewBag objects will be null
//Only TempData will exist after redirection
return View();
}
@model MvcSample.Models.Customermodel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Detail";
var tempDataCustomer = TempData["cust"] as Customer; //need typcasting
}

CheckBoxList in ASP.Net MVC3 Razor


CheckBoxList in ASP.Net MVC3 Razor

 

If we want to create many check boxes or check boxes list we can call it inside a loop as follows.

1
2
3
4
@foreach (var item in MyCollection)
{
@Html.CheckBox("checkBoxName", new {value=item.checkBoxValue })@item.CheckBoxText<br />
}

 

Here is a generic extension method for create a check boxes list in an elegant manner.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static MvcHtmlString CheckBoxList<T>(this HtmlHelper helper,
String name,
IEnumerable<T> items,
String textField,
String valueField,
IEnumerable<T> selectedItems=null)
{
Type itemstype = typeof(T);
PropertyInfo textfieldInfo = itemstype.GetProperty(textField,typeof(String));
PropertyInfo valuefieldInfo = itemstype.GetProperty(valueField);
 
TagBuilder tag;
StringBuilder checklist = new StringBuilder();
foreach(var item in items)
{
tag = new TagBuilder("input");
tag.Attributes["type"] = "checkbox";
tag.Attributes["value"] = valuefieldInfo.GetValue(item,null).ToString();
tag.Attributes["name"] = name;
if (selectedItems != null && selectedItems.Contains(item))
{
tag.Attributes["checked"] = "checked";
}
tag.InnerHtml = textfieldInfo.GetValue(item,null).ToString();
checklist.Append(tag.ToString());
checklist.Append("<br />");
}
return MvcHtmlString.Create(checklist.ToString());
}

In the first three lines we get the type of the data collection then get the property info of text field and value field that will be used to create each check box. We enumerate over the input data collection and use  TagBuilder class to create input tag and set its attributes like type,name, and value. We check the selectedItems collection to set checked attribute of our check box.

Say we have a list of users that we display it as checkboxlist to select some users, we can use our helper method as follows

1
@Html.CheckBoxList("SelectedUsers", AllUsersList, "Name", "ID")

To get the values of checked users we have two scenarios:
Strongly typed model scenario:
The model must have pro

perty with the same name that we provided to our helper method.

1
2
3
4
5
6
class MyModel
{
//Note you can define it as array of strings, dates or any primitive data type
//according to the type of the property of value field.
Public Int32[] SelectedUsers{get; set;}
}

when we post the view, the model binder will bind the values of selected check boxes into the property with the same name.

Not Strongly typed model scenario:
In this case, our action method that will handle our request(decorated by HttpPost attribute) should be defined to accept a FormCollection parameter that will contain key with the same name we provided to our helper method

1
2
3
4
5
6
[HttpPost]
public ActionResult ActionMethodName(FormCollection myForm)
{
String selectedusers = myForm["SelectedUsers"];
//Note this will return the selected users ids as comma separated string.
}

How To Get CheckBox Selected Values in Controller In MVC3


Introduction

In this article i am going to define u you how we can get selected values of checkbox in mvc3 in controller.in this article u will also get to know about multiple form in a single view how to use them.

Step 1: Make a new Empty Project using mvc3 in visual studio 2010.

Step 2: Now Add Collection Class in Model folder by Right click on model whose code would be such as below given.

 public class MyViewModel
    {
        public int Id { get; set; }
        public bool Checkbox { get; set; }
        public string Value { get; set; }
    }
 
 
    // view model for checklistbox
    public class CheckBoxListViewModel
    {
        public List<CheckListBoxItem> Items { get; set; }
 
        // the name of this list should be the same as of the CheckBoxes otherwise you will not get any result after post
        public List<string> SelectedValues { get; set; }
    }
 
    // represents single check box item
    public class CheckListBoxItem
    {
        public string Value { get; set; }
        public string Text { get; set; }
        public bool IsCheck { get; set; }
    }

Step 3: After this add a HomeController in Controller Folder and write in that below given code.

public ActionResult Index()
        { 
 
            var list = new List<MyViewModel>
            {
                new MyViewModel { Id = 1, Checkbox = false ,Value="Coal"},
                new MyViewModel { Id = 2, Checkbox= false ,Value="Cotton"},
                new MyViewModel { Id = 3, Checkbox = false ,Value = "Fabric"},
            };
            var outObj = list.Select(row => new SelectListItem()
                            {
                                Text = row.Value,
                                Value = row.Id.ToString(CultureInfo.InvariantCulture),
                                Selected = row.Checkbox
                            });
            ViewBag.keydata = outObj;
            // pass ViewModel object to View for display
 
            return View();
        }

Step 4 :  Now Add your view index.cshtml in view folder and paste in his below given code.

@{
    ViewBag.Title = "Index";
    var obj = ViewBag.keydata;
}
@using (Html.BeginForm("Index", "Home"))
{
    IEnumerable<SelectListItem> ct = ViewBag.keydata;
    foreach (var item in ct)
    {
    @Html.CheckBox("chk", item.Selected, new { value = item.Value });<label>@item.Text</label>
    }
<div>
       <input type="submit" value="Send" name="action:Send" /></div>
}

Step 5:  Now Make your Index Action with HttpPost Attribute in Controller which is below given.

 [HttpPost]
        [MultipleButton(Name = "action", Argument = "Send")]
        public ActionResult Index(FormCollection obj)
        {
           
            if (obj != null)
            {
                string[] AllStrings = obj["chk"].Split(',');
                foreach (string item in AllStrings)
                {
                    if (item.Contains("false"))
                    {
 
                    }
                    else
                    {
                        var outk = item;
                    }
 
 
 
                    // handle value
                }
            }
           
            return RedirectToAction("Index", "Home");
        }
Now Run by pressing f5 and See by putting Result in Your action you will get your all selected
Check boxes values.

If you Want to Download complete source of this article you can get to download it by click on below given url

https://docs.google.com/file/d/0B-sDsBkcsM1YWV9PWVUwYlVHRjA/edit?usp=sharing