Showing an Image on a masterpage based on the logged in user
So I have a masterpage that has an image whos source is a controller action returning a filestream.
The image will be different for each logged in user.
right now in my masterpage view i have this code wich relies on viewdata.
<img id="dealerlogo" src='/Files/DealerImage/GetDealerLogo/<%=Html.Encode(ViewData["dealerid"]) %>' alt="" />
obviously the problem with this is that I will need to provide the viewdat开发者_开发百科a containing the ID on everycontroller action returning a view that uses this master page, which is pretty much all of them. Is there a better way to do this? Like is there a way to get the username right in the view? Thanks!
You can easily encapsulate this logic in a [ChildActionOnly]
Action that returns a partial view and then use new MVC 2 approach
<% Html.RenderAction("GetUserPhoto", "User"); %>
to have it everywhere in your view pages without passing ViewData in all actions.
Here's the solution:
[ChildActionOnly]
public ActionResult GetUserPhoto()
{
ViewData["UserId"] = Page.User.Identity;
return PartialView();
}
And in your view you use the same logic you used to show user image. Also you can directly send a FileResult to partial view to render image for you. In this approach you don't need to repeat ViewData["XXXX"]
in all views and you need just to Render the new Partial View in your main Views.
You can use the Page.User.Identity.Name just like in the default logonusercontrol.aspx that is created for you when you create a new asp.net MVC site.
Welcome <b><%= Html.Encode(Page.User.Identity.Name ) %></b>
So for you, you would want something like this:
<img id="dealerlogo" src='/Files/DealerImage/GetDealerLogo/<%=Html.Encode(Page.User.Identity.Name) %>' alt="" />
I assume your GetDealerLogo action method has a parameter of dealerid. It's better to write something like:
<img src="<%= Url.Action("GetDealerLogo", "DealerImage", new { dealerid = ViewData["dealerid"] }) %>" />
Nothing wrong with passing it in via ViewData. You might also consider a strongly-typed View or your own ViewPage base class which exposes a DealerId property.
To make it even cleaner, I really like T4MVC. It would allow you to write:
<img src="<%= Url.Action(MVC.DealerImage.GetDealerLogo(dealerid)) %>" />
And, even further, you might create an Html helper, so you can write:
<%= Html.DealerLogo(dealerid) %>
精彩评论