c# - How to show the current user using ASP MVC and EF -
developing asp .net mvc 3 application using c# , sql server 2005. using entity framework code first method.
i have interface log on (connection) related base have user table (contain login + password).
i want show current user logged. so, created viewmodel class user didn't result. tried in controller :
public actionresult logon() { var user = new userviewmodel(); user.nom_user = this.user.identity.name; viewdata["userdetails"] = user; return view(); }
and add in master page :
<% var user = viewdata["userdetails"] mvcapplication2.viewmodels.userviewmodel; %> hello : <%: user.nom_user %>!
when execute, have error :
object reference not set instance of object.
you said placed code in masterpage. means run every view.
but have set viewdata["userdetails"]
inside logon
action. when navigate other action (such home/index action example) bomb because there's nothing inside viewdata["userdetails"]
, of course user
variable declared in masterpage null.
i recommend using child action that.
[childactiononly] public actionresult logedinuser() { if (!request.isauthenticated) { return partialview(); } var user = new userviewmodel(); user.nom_user = user.identity.name; return partialview(user); }
and in masterpage:
<% html.renderaction("logedinuser", "account"); %>
or if prefer:
<%= html.action("logedinuser", "account") %>
and have corresponding logedinuser.ascx
partial typed view model:
<%@ control language="c#" inherits="system.web.mvc.viewusercontrol<userviewmodel>" %> <% if (model != null) { %> <div>hello : <%= html.displayfor(x => x.nom_user) %></div> <% } %>
phil haack blogged child actions in more details here
.
Comments
Post a Comment