Reputation: 1835
I have a model which has the CRUD View. When a user inserts data into the database I would like to automatically add two pieces of information. The User who added the information and the Timestamp. Now the Timestamp is easy enough but I am having problems with the User.
I thought about accessing the Current Logged In User within the Model itself which I have not found a way of doing yet. Or perhaps (not tried yet - just thought about it) populating a hidden field in the View with the user's details.
To me having the data in the model would seem more secure than in the view which can be manipulated by the end user; which I don't think can happen with the model.
Anyway - the Questionw: 1) Should I have the AddedBy property in the Model set to the Username within the model or within the view?
2) If it should be done within the model ... how can I access the User's data?
Thanks.
Upvotes: 1
Views: 685
Reputation: 352
Default project setup would give you dbo.AspNetUsers for storing your user IDs. Or, you may have something you customized.
Your model would need to reference UserName ... for register (if allowed) and for login. This is where the user enters whatever login they choose (or where someone assigns it for them). At this point, the user should be able to correct any typos or make a name change. You may have elected to not allow this. But if you want the user name to show up, it has to be available somewhere.
To keep the user from making changes at the point they are entering data, you can set the field to display or hidden. That way, you are still going to capture the userID but not give them any opportunity to change it.
In your view you can use: @Html.DisplayName(User.Identity.Name) or User.Identity.GetUserName()
to display the name.
If you don't want the user to see their own name??? set the field as hidden @Html.HiddenFor(User.Identity.Name)
For the create view(s):
@Html.TextBoxFor(model => model.UserName, new { Value = User.Identity.Name, @Type="Hidden"} )
and for the date/time:
@DateTime.Now.DayOfWeek
@DateTime.Now.ToString("MM/dd/yyyy hh:mm tt")
@Html.TextBoxFor(model => model.LogDate, new { Value = @DateTime.Now, @Type = "Hidden" })
Make sure you reference the field values you want included in database in your "bind" statement in your controller.
Upvotes: 1