简体   繁体   中英

Showing results from stored procedure on view

I'm trying to show the results from a stored procedure on a view. I have a ASP.NET MVC application with the following code. I used EntityFramework to generate the models.

public class ProjectsController : Controller
{
    private DatabaseEntities db = new DatabaseEntities();

    // GET: Projects
    public ActionResult Index()
    {
        var projects = db.Projects.Include(p => p.Headquarter);
        return View(projects.ToList(), db.CALCULATEBUDGET());
    }
}

I get the following errors on this part: db.CALCULATEBUDGET()

Argument 1: cannot convert from 'System.Collections.Generic.List<TestApplication.Models.Project>' to 'string'   TestApplication C:\TestApplication\TestApplication\Controllers\ProjectsController.cs    21  Active


Argument 2: cannot convert from 'System.Data.Entity.Core.Objects.ObjectResult<TestApplication.Models.CALCULATEBUDGET_Result>' to 'string' TestApplication   C:\TestApplication\TestApplication\Controllers\ProjectsController.cs 21 Active

My stored procedure:

CREATE PROCEDURE dbo.CALCULATEBUDGET  
AS  
SELECT MonthlyRent, Budget, 100 * H.MonthlyRent/P.Budget AS RentPercentage
FROM Headquarter H, Project P
WHERE H.HeadquarterId = P.Headquarter_HeadquarterId

I'm trying to calculate how much percent the rent is from the budget. And then I want to show the results in a view.

first of all, when you return a View you need to either pass the name or leave it empty and then it works out using the defaults. You can pass a model as well, but what you've done is to pass two data items. The first one needs to be a View name:

return View( "YourViewName", yourDataModel);

The main concept of MVC is this : here is a View and here is the data for a View in the form of a model.

Directly throwing objects from a database at a view is usually a bad idea, I would suggest you decouple your things a little bit.

Have a business layer where you get the data, you map into a model object which matches what the view needs to display. Think of that as a translation layer from what your data looks like and what your View needs to display. Rule of thumb, only send to a View whatever it needs to display and nothing more.

You can combine multiple multiple data items in one data model for the View if that's what you need, but you still pass just one object to your View.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM