0

It is said that the models should be fat and the Views should be thin.We put our business logic inside the Model (https://stackoverflow.com/questions/235233/asp-net-mvc-should-business-logic-exist-in-controllers).We normally write the LINQ inside the controller,but is it possible that we should write the query in models,If yes then how we will get the results in the View?

Second Question

  public ActionResult Index()
  {
            using (NORTHWNDEntities c = new NORTHWNDEntities())
            {

                var x = c.Employees.Count();
                ViewData["count"] = x;

                return View(x);       
            }
    }

When we do this are we passing the variable x to the View? I tried to access the ViewData in View

<% ViewData["count"] %>

But it gives an error error ,Anyone who can help me with this Thanks

4

3 回答 3

2

If you are trying to display the value of ViewData["count"] in your view, you can use the following syntax:

<%= ViewData["count"] %>

Note the = in the opening tag. This is the equivalent of

<% Response.Write(ViewData["count"]) %>
于 2012-06-01T17:52:49.943 回答
2

there is better approach for doing this.and is very straight forward.create a Model that meets your needs and pass it to view.

public class MyModel
{
    public int Count{get;set;}
}

and your controller can looks like

public ActionResult Index()
  {
            using (NORTHWNDEntities c = new NORTHWNDEntities())
            {

                var x = c.Employees.Count();
                var model = new MyModel{Count = x};    
                return View(model);       
            }
    }

and then create an strongly typed view

Razor Syntax :

@model MyModel

@Model.Count

ASPX syntax :

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Models.MyModel>" %>
<%= Model.Count %>

and the code can get even better if you do the following:

public class EmployeeService
{

     public int GetEmployeeCount()
     {
            using (NORTHWNDEntities c = new NORTHWNDEntities())
            {
                var count = c.Employees.Count();                   
                return count;       
            }
     }
}

and the controller most change as well:

public ActionResult Index()
  { 
                EmployeeService srvc = new EmployeeService();
                var x = srvc.GetEmployeeCount();
                var model = new MyModel{Count = x};    
                return View(model);   
  }
于 2012-06-02T17:06:42.887 回答
0

The query have to be into the Data Access Layer and the logic in MVC is into the Controller, not into the Model.

Here you can find an example of a layered architecture with MVC.

At the end you have always to use a Model into the View, don't pass data using the ViewData.

于 2012-06-01T17:54:25.427 回答