如何将两组数据传递给ASP.NET MVC中的视图?
我已经尝试过几件事而且都没有工作,所以我得出了一个简单的结论:我做错了。
我有2个查询:
callRepository.FindOpenCalls()
和callRepository.FindAllMyCalls(user)
我希望通过2个局部视图(分别为OpenCalls.ascx和AssignedCalls.ascx)将两组数据放到一个视图中。
我想使用CallsController.vb中的Index()函数执行此操作。
目前我有:
'
' 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
显然只返回open调用,但我想返回viewOpenCalls和viewMyOpenCalls。
我该怎么做呢?
会显示我的LINQ帮助吗?
感谢您提前提供任何帮助。
答案 0 :(得分:2)
将数据传递到视图的最佳方法是为视图实际提供特定的ViewData,仅包含所需的数据。
而不是使用魔术字符串(ViewData("MyOpenCallCount")
)来定义包含此视图所需的所有数据的特定类(对不起,如果我的VB.Net有点生锈):
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
并使用源自ViewPage(of CallViewData)
的强类型视图,这样您就可以智能感知并且不需要使用硬编码字符串来获取您的信息。
使用来自所有呼叫和当前用户呼叫的信息填充CallViewData,返回此实例。
Dim data as new CallViewData
data.AllCalls = new CallInfo {OpenCallCount = ... }
'etc
return View(data)
答案 1 :(得分:0)
您不必像往常一样将数据项分配给ViewData。如果由于某种原因你无法传递CallRepository对象,那么你可以创建另一个数据对象来保存你的open和所有调用存储库数据并传递它。
从长远来看,这是一种实际上更加灵活的设计。
答案 2 :(得分:0)
您可以将ViewData存储在模型对象中并传递它。这is explained very well in PRO ASP.NET MVC chapter 9。