Posts Tagged Populate

How to populate Angular UIGrid in MVC using AngularJS

Description

In this article I will explain the steps for populating UI-Grid in angularjs from database using WebAPI. UI-grid is a powerfull tool which provides a table like representation. Apart from table like structure Ui-Grid also provides functionality like filtering, sorting, exporting etc.  You can find more details about UI-Grid from here

PreRequisites:

Ui-Grid is dependant on AngularJS.Hence ensure that you have added reference of Angular js on page.

Implementation:

Model:

To load the data from database, we are using EntityFramework and its related method. In this example I have used the DatabaseFirstApporach.  DatabaseFirstApporach lets the EnityData Model to generate classes, dbcontext etc from the database automatically. All other functionalities like database and model sync exists as is.

Follow the below procedures to generate Model for Customer database in Northwind database

  • Right click on the Model folder
  • Select Add option
  • And then select the New Item option
  • Choose Data from Installed Templates group
  • Select the ADO.NET Entity Data Model option and Provide a name for it
  • In the Entity Data Model Wizard, Select EF Designer from database and click on Next
  • Choose the Connection string options
    • If you already have connection string configured then you can select that from the available list.
    • If you don’t have the connection string configured then use the New Connection option and create the connection
  • Expand the Table option and then select the tables which you want
  • Click on Finish

You will have necessary class files generated in your solution now

Northwind

You can get more details about how to use DatabaseFirst approach from this link.

Controller (WebAPI)

In this example we are using WebAPI to load the data. The next procedure is to write code to fetch records from database using WebAPI.  For this demo I have used a basic select operation. You can modify this as per your need.

Another point to note here is UI-grid read data which is in Json format, Hence we need to ensure that the data which we return from controller is of Json format. We will use the JsonResult method for this.

View:

On View we will have the codes for UI-Grid and its related files. If you look at the design of UI-Grid it’s a div which will be styled to look like a table at runtime.

We need to add div with an attribute as ui-grid=”gridOptions”.  We add all the details from angular js code to gridOptions and UI-Grid at runtime uses this div to populate the grid.

RouteConfig Changes:

I have changed the Action Name from “Get” to “GetCustomer” to be more specific with what the method do. In order for api to identify the proper method add the below route setting to web api route config

Angular JS Script

Below are the code to fetch the data from database and populate it to UI-Grid. I have used a factory to call the Get Customer method and used that in the main method.

 

, , , , ,

1 Comment

how to create Cascading Dropdown list in Asp.Net

Introduction

In this article I am going to explain how to create Cascading Dropdown list in Asp.net from database. The Cascading Dropdown list loads data based on the value selected in parent dropdown list.

For ex: if you have Dropdownlist1 and Dropdownlist2 then Dropdownlist2 will be populated based on the value selected in Dropdownlist1.

Complete Code:

To load data based on the value selected in dropdown list, we will be using the SelectedIndexChanged event in dropdown list and then load the data in dropdown list.

HTML:

In Dropdownlist1 we will be using selectedindexchanged event to fill the dropdownlist2.

asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
                        AutoPostBack="true">
                    </asp:DropDownList>
                    

                    <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
                </ContentTemplate>
            </asp:UpdatePanel>

C#:

First dropdownlist we will populate as we normally populate the dropdownlist from database like given below

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Load the first dropdownlist
                LoadDropDown();
            }
        }
        //This method is used to load the first dropdownlist
        public void LoadDropDown()
        {
            //Get your connection string
            string connstring = ConfigurationManager.ConnectionStrings["Adventure WorksConnectionString"].ToString();
            //Create connection here
            using (SqlConnection conn = new SqlConnection(connstring))
            {
                //Sample Query here; You need to update the query as per your need
                string sqlquery = "SELECT TOP 100 a.city as City FROM Person.Address a";
                //Create SQLCommand object
                using (SqlCommand cmd = new SqlCommand(sqlquery, conn))
                {
                    //Open the SQLConnection
                    conn.Open();
                    //Execute the query
                    SqlDataReader rdr = cmd.ExecuteReader();

                    //Assign the values to dropdownlist
                    DropDownList1.DataSource = rdr;
                    //Set the DataValueField of dropdownlist
                    DropDownList1.DataValueField = "City";
                    //Set the DataTextField of dropdownlist
                    DropDownList1.DataTextField = "City";
                    //Bind the dropdownlist
                    DropDownList1.DataBind();
                }
            }
        }

Populating the second Dropdown list:

Here basically we will get the dropdown list values from database based on the value selected in dropdownlist like given below

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Get your connection string
            string connstring = ConfigurationManager.ConnectionStrings["Adventure WorksConnectionString"].ToString();
            //Create connection here
            using (SqlConnection conn = new SqlConnection(connstring))
            {
                //Sample Query here; You need to update the query as per your need
                string sqlquery = "SELECT TOP 100 a.AddressLine1 as AddressLine FROM Person.Address a where a.City =@City";
                //Create SQLCommand object
                using (SqlCommand cmd = new SqlCommand(sqlquery, conn))
                {
                    //Open the SQLConnection
                    conn.Open();

                    //Pass the value selected in previous dropdownlist as parameter to this query
                    cmd.Parameters.AddWithValue("@City", DropDownList1.SelectedItem.Text);
                    //Execute the query
                    SqlDataReader rdr = cmd.ExecuteReader();

                    //Assign the values to dropdownlist
                    DropDownList2.DataSource = rdr;
                    //Set the DataValueField of dropdownlist
                    DropDownList2.DataValueField = "AddressLine";
                    //Set the DataTextField of dropdownlist
                    DropDownList2.DataTextField = "AddressLine";
                    //Bind the dropdownlist
                    DropDownList2.DataBind();
                }
            }
        }

Demo

, , , , ,

1 Comment

How to load Dropdownlist from database in MVC or Populate Dropdownlist in MVC from database

Introduction:

In this article I am going to explain an easy way to populate dropdownlist in MVC.  There are lots of other options to populate dropdownlist in MVC, However here I am going to explain two options which I have come across.

Solution:

Model:

First you need to create a class in the Model. In this example I have used the DatabaseFirst approach.

You can use the below steps to generate the class files

  • Right click on the Model folder
  • Select Add option
  • And then select the New Item option
  • Select the Net Entity Data Model option and Provide a name for it
  • In the Entity Data Model Wizard, selectEF Designer from database and click on Next

If you already have connection string configured then you can select that from the available list.

If you don’t have the connection string configured then use the New Connection option and create the connection

  • Expand the Table option and then select the tables which you want
  • Click on Finish
  • You will have necessary class files generated in your solution now

Untitled

You can get more details about how to use DatabaseFirst approach from this link.

Controller:

Once the needed model files are generated now we need to create the code to get the data from database and then pass it to view for dropdownlist.

You can use the below code to get the value from database and pass it to ViewBag

 public ViewResult Index()
         {
             //Create db context object here 
             AdventureWorksDbContext dbContext = new AdventureWorksDbContext();
             //Get the value from database and then set it to ViewBag to pass it View
             IEnumerable<SelectListItem> items = dbContext.Employees.Select(c => new SelectListItem
                   {
                       Value = c.JobTitle,
                       Text = c.JobTitle
 
                   });
             ViewBag.JobTitle = items;
             return View();
         }
 

View:

Now you need to assign the values in ViewBag to dropdownlist like given below

@Html.DropDownList("JobTitle", "Select a Value")

You will have the dropdownlist populated with data now

, , , , ,

6 Comments