Display data in View from Stored Procedure using Model in ASP.Net MVC

Last Reply 5 months ago By dharmendr

Posted 5 months ago

hello,

Call Stored Procedure of Complex Type using Entity Framework in ASP.Net MVC 

i am following this artilce it works the only problem the VIEW is bind directly with sp funciton i want to get the restul of SP functions in List of my view model in controller then my VIEW should be bind with view model instead of directly SP functions pls advice

Posted 5 months ago

Hi nauna,

Using the below link i have created the example.

Call Stored Procedure of Complex Type using Entity Framework in ASP.Net MVC

Check this example. First i have created the Complex Type to return the stored procedure result as ObjectResult.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

SQL

CREATE PROCEDURE [dbo].[Customers_GetCustomersOrder]
AS
BEGIN 
  SELECT TOP 10
         O.CustomerID,
         C.ContactName,
         C.City
  FROM Customers C
  INNER JOIN Orders O ON C.CustomerID = O.CustomerID
END

Model

public class CustomerModel
{
    public List<CustomerDetail> Customers { get; set; }
}
public class CustomerDetail
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        NorthwindEntities entities = new NorthwindEntities();
        var result = entities.CustomerOrders();
        List<CustomerDetail> customers = new List<CustomerDetail>();
        foreach (var item in result)
        {
            customers.Add(new CustomerDetail { Id = item.CustomerID, Name = item.ContactName, City = item.City });
        }
        CustomerModel model = new CustomerModel();
        model.Customers = customers;
        return View(model);
    }
}

View

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<_Display_Stored_Procedure_Result.Models.CustomerModel>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Index</title>     
</head>
<body>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>City</th>
        </tr>
        <% foreach (var item in Model.Customers)
           { %>
        <tr>
            <td><%: item.Id %></td>
            <td><%: item.Name %></td>
            <td><%: item.City %></td>
        </tr>
        <% } %>
    </table>
</body>
</html>

Screenshot