Tuesday, 2 September 2014

Bind DropDownList In MVC WebGrid and Retrive Value Using Asp.net MVC, C#.Net

9/02/2014 - By Pranav Singh 11

This will show you how you can use a use dropdown list inside an MVC webgrid. This article will explain you how you can Bind DropDownList In MVC WebGrid and Retrive Value Using Asp.net MVC, C#.Net. This article you can use in MVC3,MVC4,MVC5.


So for this article first we will create a new asp.net mvc application and add a model class files into the module folder. So here is the model class file code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication6.Models
{
    public class StudentModel
    {
        public List<Student> StudentList { get; set; }
    }
    public class Student
    {
        public string Name { get; set; }
        public string ClassOfStudent { get; set; }
        /*For student section collection*/
        public SelectList SectionModel { get; set; }
        public string StudentSection { get; set; }
        public string Address { get; set; }
    }
}

Now again come to your application and add a controller class file into the controller folder. Now use the below code into your controller folder.

using System.Collections.Generic;
using System.Web.Mvc;

namespace MvcApplication6.Models
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            StudentModel _objstudentmodel = new StudentModel();
            _objstudentmodel = StudentRecord();
            return View(_objstudentmodel);
        }
        [HttpPost]
        public ActionResult Index(StudentModel _objstudentmodel)
        {
            List<string> stusection = new List<string>();
            stusection = GetSectionList();

            foreach (var item in _objstudentmodel.StudentList)
            {
                SelectList objsection = new SelectList(stusection, item.StudentSection);
                item.SectionModel = objsection;
            }
            return View(_objstudentmodel);
        }
        ///



        /// This function will return data for webgrid
        ///
public StudentModel StudentRecord()
        {
            List<string> stusection = new List<string>();
            stusection = GetSectionList();

            SelectList objsection = new SelectList(stusection);
            StudentModel _objstudentmodel = new StudentModel();
            _objstudentmodel.StudentList = new List<Student>();
            _objstudentmodel.StudentList.Add(new Student { Name = "Name1", ClassOfStudent ="12th", SectionModel = objsection, Address = "Address1" });
            _objstudentmodel.StudentList.Add(new Student { Name = "Name2", ClassOfStudent ="5th", SectionModel = objsection, Address = "Address2" });
            _objstudentmodel.StudentList.Add(new Student { Name = "Name3", ClassOfStudent ="10th", SectionModel = objsection, Address = "Address3" });
            _objstudentmodel.StudentList.Add(new Student { Name = "Name4", ClassOfStudent ="1st", SectionModel = objsection, Address = "Address4" });

            return _objstudentmodel;
        }
        ///



        /// This function will return data for dropdown
        ///
        ///
        public List<string> GetSectionList()
        {
            List<string> StuSection = new List<string>();
            StuSection.Add("A");
            StuSection.Add("B");
            StuSection.Add("C");
            return StuSection;
        }
    }


}
        
In above code please check the above code in this code first I will discuss two functions StudentRecord and GetSectionList. In this first function StudentRecord is used for getting the record for binding the webgrid, and GetSectionList is used for assigning the dropdown list data.

Now please check the Inex action result for populating data on page load and httppost methos to get the selected value of dropdown list on postback.  In httppostwe have retrieved the value selected in dropdownlist and then we have assign the selected value to the select list. This we are doing because when post back take place we want to retain the selected value of dropdown list inside the webgrid.

Now we will create the view of index actionresult. Add the below code into your view.

@model  MvcApplication6.Models.StudentModel
@{
    ViewBag.Title = "Bind DropDownList In MVC WebGrid and Retrive Value Using Asp.net MVC, C#.Net";
}
<style type="text/css">
    table
    {
        font-family: verdana,arial,sans-serif;
        font-size: 11px;
        color: #333333;
        border-width: 1px;
        border-color: #666666;
        border-collapse: collapse;
    }
    table th
    {
        border-width: 1px;
        padding: 8px;
        border-style: solid;
        border-color: #666666;
        background-color: #dedede;
    }
    table td
    {
        border-width: 1px;
        padding: 8px;
        border-style: solid;
        border-color: #666666;
        background-color: #ffffff;
    }
    input
    {
        width: 60px;
    }
</style>
@using (Html.BeginForm("Index", "Home"))
{

    var grid = new WebGrid(Model.StudentList, canSort: false, canPage: false);
    int rowNum = 0;
    <div>
        @grid.GetHtml(columns:
            grid.Columns
            (
                grid.Column("RowNumber", format: item => rowNum = rowNum + 1),
                grid.Column("Name", format: (item) => Html.TextBox("StudentList[" + (rowNum - 1).ToString() + "].Name", (object)item.Name)),
                grid.Column("Class", format: (item) => Html.TextBox("StudentList[" + (rowNum - 1).ToString() + "].ClassOfStudent", (object)item.ClassOfStudent)),
                grid.Column("Section", format: @item => Html.DropDownList("StudentList[" + (rowNum - 1).ToString() + "].StudentSection", (IEnumerable<SelectListItem>)Model.StudentList[rowNum - 1].SectionModel)),
                grid.Column("Address", format: (item) => Html.TextBox("StudentList[" + (rowNum - 1).ToString() + "].Address", (object)item.Address))
            ), mode: WebGridPagerModes.Numeric)
    </div>
    <input type="submit" value="Submit" />
   
   
}

In above  code we have created dynamic name of each control present inside the webgrid. We are creating dynamic name because when postback take place at that time we will be able to access the added and selected value inside the webgrid.

Please check the below view code. This code is used for binding the dropdown.


grid.Column("Section", format: @item => Html.DropDownList("StudentList[" + (rowNum - 1).ToString() + "].StudentSection", (IEnumerable<SelectListItem>)Model.StudentList[rowNum - 1].SectionModel))

Now run the application and check the view source of the page you will get the control name in array form. This array name is responsible for accessing the value.

<tr>
    <td>
        1
    </td>
    <td>
        <input id="StudentList_0__Name" name="StudentList[0].Name" type="text" value="Name1" />
    </td>
    <td>
        <input id="StudentList_0__ClassOfStudent" name="StudentList[0].ClassOfStudent" type="text"
            value="12th" />
    </td>
    <td>
        <select id="StudentList_0__StudentSection" name="StudentList[0].StudentSection">
            <option>A</option>
            <option>B</option>
            <option>C</option>
        </select>
    </td>
    <td>
        <input id="StudentList_0__Address" name="StudentList[0].Address" type="text" value="Address1" />
    </td>
</tr>
<tr>
    <td>
        2
    </td>
    <td>
        <input id="StudentList_1__Name" name="StudentList[1].Name" type="text" value="Name2" />
    </td>
    <td>
        <input id="StudentList_1__ClassOfStudent" name="StudentList[1].ClassOfStudent" type="text"
            value="5th" />
    </td>
    <td>
        <select id="StudentList_1__StudentSection" name="StudentList[1].StudentSection">
            <option>A</option>
            <option>B</option>
            <option>C</option>
        </select>
    </td>
    <td>
        <input id="StudentList_1__Address" name="StudentList[1].Address" type="text" value="Address2" />
    </td>
</tr>

Now we have done just run the application to check the output.


Now select the value and click on submit button your brake point and here you see we are getting the selected value which we have selected in dropdown which is present inside the webgrid.


Now press F5 and check the final output.


DOWNLOAD

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

11 comments:

  1. Hi,

    its only A showing in grid view drop down list

    this is not working property
    can you update the correct project

    ReplyDelete
    Replies
    1. Hi this article is regarding "Bind DropDownList In MVC WebGrid and Retrive Value Using Asp.net MVC, C#.Net".
      This code works properly. There is no error.

      What you trying to do.

      Delete
  2. how can i fetch data from database in dyanamic gridview textboxes???

    ReplyDelete
  3. this really work for me... how can i get data from different tables in database into this work? same display like this

    ReplyDelete
    Replies
    1. hi Please check the below link to get the data from DB
      http://www.aspdotnet-pools.com/2014/06/bindpopulate-dropdownlist-using-entity.html

      Delete
  4. Hi, I am new to MVC
    What change should I make to the View, so that I have a label for "Name" instead of a Textbox.

    ReplyDelete
  5. Hi in this example can we make dropdown enable when we click on edit button ?

    ReplyDelete
    Replies
    1. Yes
      You just need to call a js function on click of button ,which enable the ddl.

      Delete
  6. Question I have is how does one perform this if a row number field is not available?

    ReplyDelete

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top