I have a question about using Sessions in MVC.
After the user validated and before going to the index page, from the login controller I save some data into a session variable as follows:
Session["user"] = new User() { usrNme = name, usrFirstName = dataset.usrFirst, usrLastName = dataset.usrLast };
Where User is a model that represents database table. My question is, what is the best way to display only first name usrFirstName in the index page?
Thank you
You can retrieve the user object from the session like this :
User objectName = (User) Session["user"];
Note: while retrieving an object from session its important to cast
it to the object type
Then access the object to get its properties.
objectName.usrFirstName
Related
I have a project with a form that is completed over several parts. E.g. Part 1 might include your name, and part 2 your address.
In MVC I have several views which represent each of the parts and one model to hold all the form data.
I would like to save the form data at the completion of each part, and retrieve the saved record on the next part (so that the whole model is available at each stage).
I am using Post-Redirect-Get to avoid the 'form may be resubmitted' warnings from browsers using the back and forward buttons.
Controller code
[HttpGet]
[Route("Form/Part/{id}")]
public ActionResult Part(int id, int? recordId)
{
var model = new MyVM();
if(recordId.HasValue) {
// get record from DB
// map record to 'model'
}
return View("Form.{id}", model);
}
[HttpPost]
[Route("Form/Part/{id}")]
public ActionResult Part(int id, MyVM model)
{
// map model to entity
// save/update entity
return RedirectToAction($"Form/Part/{id + 1}", new { recordId = recordId })
}
My question is how best to retain the ID of the newly created / updated record and pass it to the next form part.
Whilst passing the recordId as a routeValue works, it breaks when I use the browser back button as the recordId in the querystring is lost.
I have considering storing this in the session perhaps, but don't really want to bring the HttpContext into play if I don't have to for testing reasons.
Is there a recommended way to achieve this kind of thing? Any thoughts on the various ways to keep track of the current record would be greatly appreciated.
You can either use the TempData or Session to pass Data between requests.
I Would create a big class / object with all the fields from the wizard, throw it in the session eg key "MyWizardData" and retrieve it in the other parts of the wizard.
After
// save/update entity
you have the ID, throw it in the session and grab it back in the next action.
If you dont want to use the session, get the id after save / update and store it in a field in the database in the user table. Or just store the UserId with your created entity row. Then you can grab it in any action.
I am creating a project using ASP.NET MVC 5.
I used Identity to get user information.
Using migrations I created fields like FirstName, LastName
But how do I use that? I have this:
#using MTC.Models
#helper Render(MTC.Post post, System.Web.Mvc.HtmlHelper html, bool showComments)
{
{
var user = new ApplicationUser();
user.FirstName.ToString();
}
}
And it returns this:
System.NullReferenceException: Object reference not set to an instance of an object.
All I want to do is get it to display the name from the database.
I am trying to learn the backend. Sorry If this is completely wrong.
you are creating new object of ApplicationUser without initializing its values. So every property of this object will be null. You need to either first assign value to it or fetch user from database.
You can do this by creating UserID column in your table along with Names of user and get User Name from the table by:
string Name = User.Identity.GetUserId();
return View(Database.Table.Where(r =>r.UserID == Name).ToList());
You can do this in your controller and also in your view.
i have a MVC application that contains an ASPX page that will be called in single sign on mode.
How can i set the user that is passed by a request call?
I tried to use "Identity" with no fortune.
example:
string username = "MyUsername";
string userid = Guid.NewGuid().ToString("N"); //could be a constant
List<Claim> claims = new List<Claim>{
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", username),
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userid)};
var genericIdentity = new GenericIdentity(username);
genericIdentity.AddClaims(claims);
var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] { "aaa" });
Context.User = genericPrincipal;
The second problem is that i have some data regarding the user but i can't set to session (like expected by signalr design).
How can solve it?
Update:
After some search i understand what i really need. When the page is called i check validation of user on database and if it's verified i need to store this information in a way that is reachable everywhere. It's what i would have done with SESSION object.
For me a user is not a simple string, but it's a complex object that contains useful information for the behaviour of the program.
I hope i am clearer.
You can add state on the client proxy.
If your data is too complex for that, you need to pass it at apprpriate times using hub methods.
I am developing an ASP.Net MVC 3 Web application with Entity Framework 4. When a user logs into my application I would like to store their user entity (firstName, lastName etc) in a session which can then be access throughout the application.
I understand that this may not be a good idea because when the ObjectContext closes/ disposes, then the User entity is detached and the user details could be lost.
I thought another method could be, when the user logs in, assign the userID (Primary Key) to a session variable, ie:
HttpContext.Current.Session["currentUserID"] = user.userID;
Then create a class in the UserService class like so:
public static User CurrentUser
{
get
{
return Data.DBEntities.Users.Where(u => u.userID == HttpContext.Current.Session["currentUserID"]).FirstOrDefault();
}
}
Which should return a User Entity based on the currentUserID session variable. This isn't working for me however, I am getting a couple of errors
Cannot convert lambda expression to type 'string' because it is not a delegate type
Delegate 'System.Func<Asset.Model.User,int,bool>' does not take 1 arguments
Is this approach I am taking correct, or is there a better way?
Any feedback would be much appreciated.
First, don't store security-sensitive information in Session. Google "ASP.NET Session hijacking" for info as to why.
That said, this code can be made to work. You just have a cast error. Also, You're not accounting for the fact that Session can and does expire during a login. You could do this:
public static User CurrentUser
{
get
{
object userID = HttpContext.Current.Session["currentUserID"];
if (userID == null)
{
throw new InvalidOperationException("Oops!");
}
return Data.DBEntities.Users.Where(u => u.userID == (int)userId ).FirstOrDefault();
}
}
...which at least compiles, but isn't secure and sometimes throws.
It would be better to store the user ID on a custom principal, which is secure and doesn't expire.
You can store whole entity in Session. It will be detached but it doesn't mean that it will lost values - only in case of lazy loading you will not be able to lazy load navigation properties.
In your current code try to get your currentUserId to temporary variable and use that variable in your query.
I'm using spring security, and I need to get the User domain object in a controller.
If I call SpringSecurityService.getPrincipal(), I get back an object of type org.codehaus.groovy.grails.plugins.springsecurity.GrailsUser. However, what I'm looking for is the User domain object I've defined in my Config.groovy like so:
grails.plugins.springsecurity.userLookup.userDomainClassName = 'project.auth.User'
How can I best get at the User domain object?
Load the user instance using the cached id in the GrailsUser instance:
def user = User.get(SpringSecurityService.principal.id)