views:

51

answers:

3

How do I go about passing two sets of Data to a view in ASP.NET MVC?

I've tried a couple of things and neither have worked so I've come to the simple conclusion: I'm doing it wrong.

I have 2 queries:

callRepository.FindOpenCalls() and callRepository.FindAllMyCalls(user)

and I want to out put both sets of data to one view via 2 partial views (OpenCalls.ascx and AssignedCalls.ascx respectively).

I'd like to do this using the Index() function in my CallsController.vb.

At the moment I have:

'
' GET: /Calls/

<Authorize()> _
Function Index() As ActionResult
    ViewData("OpenCallCount") = callRepository.CountOpenCalls.Count()
    ViewData("UrgentCallCount") = callRepository.CountUrgentCalls.Count()
    ViewData("HighCallCount") = callRepository.CountHighCalls.Count()
    ViewData("NormalCallCount") = callRepository.CountNormalCalls.Count()
    ViewData("LowCallCount") = callRepository.CountLowCalls.Count()

    ViewData("MyOpenCallsCount") = callRepository.CountMyOpenCalls(Session("LoggedInUser")).Count()
    ViewData("UserName") = Session("LoggedInUser")

    Dim viewOpenCalls = callRepository.FindAllOpenCalls()
    Dim viewMyOpenCalls = callRepository.FindAllMyCalls(Session("LoggedInUser"))

    Return View(viewOpenCalls)
End Function

Which returns just the open calls obviously, but I'd like to return both viewOpenCalls and viewMyOpenCalls.

How would I go about it?

Would showing my LINQ help?

Thanks for any help in advance.

A: 

You don't have to assign data items to ViewData piecemeal the way you're doing. If for some reason you can't pass the CallRepository objects(s) then you can create and another data object which will hold your open and all calls repository data and pass that.

And that is a design that's actually much more flexible in the long run.

Paul Sasik
+2  A: 

The best way to pass data to a view is to actually have a specific ViewData for your view, containing only the data needed.

Instead of having magic strings ( ViewData("MyOpenCallCount") ) define a specific class containing all the data needed for this view (sorry if my VB.Net is a bit rusty):

public class CallInfo
    public OpendCallCount as int
    public UrgentCallCount as int 
    'etc.
end class

public class CallViewData
    public AllCalls as CallInfo
    public MyCalls as CallInfo
    public UserName as String
end class

And use a strongly typed view deriving from ViewPage(of CallViewData), this way you have intellisense and you don't need to struggle with hardcoded strings to get to your information.

You populate CallViewData with info from both all calls and the current user calls, return this instance.

   Dim data as new CallViewData
   data.AllCalls = new CallInfo {OpenCallCount = ...  }
   'etc
   return View(data)
Yann Schwartz
A: 

You can store your ViewData in a model object and pass that. This is explained very well in PRO ASP.NET MVC chapter 9.

Dan Diplo