开发者

ASP.Net MVC "logged in" best practice in view/markup

开发者 https://www.devze.com 2023-01-31 05:16 出处:网络
Quick question. If I wanted to say, have a login button if user isn\'t开发者_Python百科 logged in, and some other markup if the user is logged in, what would be the best approach?

Quick question. If I wanted to say, have a login button if user isn't开发者_Python百科 logged in, and some other markup if the user is logged in, what would be the best approach?

I'm reluctant to go with the

<% if(user.loggedIn){ %>
    <!-- do something -->
<% }else{ %>
    <!-- do something else -->
<% } %>

approach, since I hate code in my markup. Would I be way off base, if I thought a 'pretty' way to do this was to make a user control to accomplish this? and then have the code in the user control code-behind? Can anyone give me a quick 'n dirty example?


<% 
   if (Request.IsAuthenticated)
   {
%>
        Welcome <%: Page.User.Identity.Name%>!
<%
   }  else {
%>
       Login something     
<% } %>


I'm reluctant to go with the ...

right approach.

and then have the code in the user control code-behind

No, it wouldn't be any better than simple logic in the view. In fact, you can't avoid logic in the view. For presentation purposes, it's just fine. Just watch out not to go too far.


In this case the code you're writing is part of the View layer since it's dealing directly with which piece of HTML to display to the user.

If you don't like putting any code in your views then it's possible that the MVC pattern isn't what you're looking for. This kind of seperation is designed to allow you to keep view related code in views.

If your concern is more about messy code then you might want to check out the Razor View Engine that comes as part of MVC3. This is a much neater (in my opionion) way of coding your views.


I'd suggest a Partial View. That Partial View is still going to have the code in mark-up but there really isn't anything wrong with that, if there were then people wouldn't be going to so much trouble writing View engines.

If you really don't like code in mark-up then you could create two Views, one logged in and one not, redirecting the user to the appropriate one from the Action but I think you'll quickly learn to dislike that more than code in the View.

0

精彩评论

暂无评论...
验证码 换一张
取 消