How to bind the GridView with stored procedure in ASP.Net MVC ?

How to bind the GridView to a stored procedure in ASP.Net MVC ?

To bind a GridView to a stored procedure in ASP.NET MVC, you can follow these steps. This guide will demonstrate how to set up your database, create stored procedures, and implement the MVC application to display data in a GridView.

Step 1: Set Up the Database and Stored Procedures

Create a SQL Server database and a table to store the data:

sql

CREATE TABLE Products (

Id INT PRIMARY KEY IDENTITY(1,1),

Name VARCHAR(50) NOT NULL,

Price DECIMAL(18,2) NOT NULL

);

Create stored procedures for retrieving data:

sql

— Stored Procedure to get all products

CREATE PROCEDURE GetAllProducts

AS

BEGIN

SELECT FROM Products

END

Step 2: Create the Model

Create a model class named ProductModel.cs in the Models folder:

csharp

public class ProductModel

{

public int Id { get; set; }

public string Name { get; set; }

public decimal Price { get; set; }

}

Step 3: Create the Controller

Create a controller named ProductController.cs:

csharp

using System.Collections.Generic;

using System.Data;

using System.Data.SqlClient;

using System.Web.Mvc;

using YourNamespace.Models; // Update with your actual namespace

public class ProductController : Controller

{

private string connectionString = “YourConnectionStringHere”; // Update with your connection string

public ActionResult Index()

{

List<ProductModel> products = new List<ProductModel>();

using (SqlConnection conn = new SqlConnection(connectionString))

{

conn.Open();

SqlCommand cmd = new SqlCommand(“GetAllProducts”, conn);

cmd.CommandType = CommandType.StoredProcedure;

SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())

{

products.Add(new ProductModel

{

Id = (int)reader[“Id”],

Name = reader[“Name”].ToString(),

Price = (decimal)reader[“Price”]

});

}

}

return View(products);

}

}

Step 4: Create the Index View

Create the Index view named Index.cshtml:

xml

@model IEnumerable<YourNamespace.Models.ProductModel>

@{

ViewBag.Title = “Products”;

}

<h2>Products</h2>

<table class=”table”>

<thead>

<tr>

<th>Name</th>

<th>Price</th>

</tr>

</thead>

<tbody>

@foreach (var product in Model)

{

<tr>

<td>@product.Name</td>

<td>@product.Price</td>

</tr>

}

</tbody>

</table>

Step 5: Configure the Connection String

Update the connection string in the Web.config file:

xml

<connectionStrings>

<add name=”DefaultConnection” connectionString=”Data Source=YOUR_SERVER;Initial Catalog=YourDatabaseName;Integrated Security=True” providerName=”System.Data.SqlClient” />

</connectionStrings>

Step 6: Run the Application

Start the application and navigate to the products page (e.g., /Product/Index).

The GridView will display the data retrieved from the stored procedure.

Algorithm: Binding GridView to Stored Procedure (ASP.Net MVC)

This algorithm outlines the steps for binding a GridView control in ASP.Net MVC to data retrieved from a stored procedure.

1. Model Definition

  • Define a model class representing a single data record displayed in the GridView.
  • The model properties should correspond to the columns returned by your stored procedure.

2. Stored Procedure Creation

  • Create a stored procedure to retrieve the data you want to display in the GridView.
  • This stored procedure should take any necessary parameters as input (optional).

3. Database Connection (Optional):

  • Establish a connection string in your web.config file to connect to the database.
  • Alternatively, use dependency injection to manage database connections.

4. Controller Implementation:

A. Index Action Method:

  • Create an action method named Index to display the initial GridView.
  • Use Entity Framework or another data access layer to call the stored procedure.
    • Pass any required parameters to the stored procedure call.
  • Retrieve the data returned by the stored procedure as a collection of model objects.
  • Pass the retrieved data collection to the view as a model.

5. View Implementation (cshtml):

A. GridView:

  • Use the @Html.GridView helper to render the GridView control.
  • Set the DataSource property to the model collection passed from the controller’s Index action method.
  • Define columns for each model property you want to display.

B. Data Binding:

  • Use data binding syntax (@Model.<property>) within the GridView column definitions to bind data from the model properties to the GridView columns.

6. Optional: Handling Empty Results

  • Implement logic in the view to handle scenarios where the stored procedure returns no data.
    • You can display a message or hide the GridView if no data is available.

Benefits:

  • Simplifies data retrieval and display within your ASP.Net MVC application.
  • Promotes code separation by keeping data access logic in the controller.

Note: This is the basic algorithm. The specific implementation specifics will depend on your stored method parameters, model structure, and desired GridView settings.

Summary

This tutorial shows how to tie a GridView in ASP.NET MVC to a stored method. The method entails building a SQL Server database and stored procedures, configuring a model, and implementing a controller to retrieve and pass data to the view. The data is then shown in a table manner. You can improve this implementation by including pagination, sorting, and editing tools.

Leave a Comment

Your email address will not be published. Required fields are marked *