I hav开发者_如何学编程e a partial (user control) that shows a menu of links. It lives on my masterpage. If you are an admin, you should see a different menu from others.
I have a method in my Member class called: IsAdmin(). Normally it would be very easy to just put some logic in the partial declaratively to show the right menu if someone is an admin, such as:
<% if (member.IsAdmin()) { %>
But since I am using Ninject for dependency injection and my Member class cannot be instantiated without the required dependencies (an IMemberRepository) I am not sure how to do this in my partial. I know that Ninject can supply a the repository to my Controller class' constructor, but I do not knowhow to do this in a partial.
In my opinion view injection should not be used at all because it is hardly testable by unit tests. Consider to change the design and let the controller change the view model instead and use the view model to decide what is shown.
If you really want to do view injection there is an example in the MVC3 sample application: https://github.com/ninject/ninject.web.mvc/tree/master/mvc3/src/SampleApplication/Views/Math
I was in this same predicament last week, as i have a partial that provides a list of 'top locations' to various views.
Ensure that the controller is injected with the necessary service or repository to provide the partial with the data it requires, then pass it to the view as a dynamic viewdata property (in mvc3)...
public class LocationController : Controller
{
private readonly ILocationService _svc;
public LocationController(LocationService svc)
{
_svc = svc;
}
public ActionResult Index()
{
//get data for 'top locations' partial
var topOnes = svc.GetTopLocations(10);
ViewData.TopLocations = topOnes;
//mvc2 would be ViewData["TopLocations"] = topOnes;
//get 'main' view data
var location = svc.GetDefaultLocation();
return View(location);
}
Or, more formally, include it in the view model that your controller returns.
I figured it out. In my partial I put the following in:
IKernel kernel = new StandardKernel(new NinjectControllerFactory.MyServices());
MembershipService membershipService = new MembershipService(kernel.Get<IMemberRepository>());
And now I can do the following:
if (Request.IsAuthenticated && membershipService.IsAdmin())
{
精彩评论