I have a razor .cshtml view in MVC4 and I want to print a field of my userprofile class. I understand I can get the Username from User.Identity.Name but I don't know how to access the other properties of the currently logged in user in the partial. Do I need to do this in my controller and reference it in my view? If so is there a controller that is available to all views so I am not setting this variable in every controller? Is there a simple way to access the current users properties as defined in the UserProfile model class right in the view? To give some context. I have my model as...
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
//Added to round out requirements for site user profile
public string FirstName { get; set; }
public string LastName { get; set; }
public string Site { get; set; }
}
I need to access the FirstName in the view. If I get it in the controller then I will need to do it in all controllers since this is a page partial for all pages.
I decided to put it in a session variable since it is not critical, sensitive, or effects the stability of the application. In my controller on login or registration I set the session variable with...
var context = new UsersContext();
var curuser = context.UserProfiles.First(p => p.UserName == model.UserName);
Session["FName"] = curuser.FirstName;
I got this from Pro ASP.NET MVC and from this post. And in my Razor view I use this derived from this post.
#HttpContext.Current.Session["FName"].ToString()
In the controller action that is serving the partial view put FirstName in the ViewBag.
If there are more properties that you would like to return then create a ViewModel for them and make the controller action return that.
Related
Using EF 7 I have an object that references a many to many table, using code first method.
public class EventUser
{
public string UserId { get; set; }
public User User { get; set; }
public int EventId { get; set; }
public Event Event { get; set; }
public string AdditionalInfo { get; set; }
}
I can pull a list of these when knowing EventId and display them in Razor. I want to link to each one of these objects back to the controller so a user could edit the AdditionalInfo field. Since the object doesn't have just one Id field, how can I send the appropriate data to the controller to access this object, since just using one Id will not be enough.
At this point, I can achieve this using:
<a asp-action="EditEventUser" asp-route-EventId="EventUser.EventId" asp-route-UserId="EventUser.UserId">Edit Event User</a>
But, I would like to know if I am ignorant about some other way this can be achieved in a cleaner way (if there is such a way).
I have 2 model classes contactdetails.cs and empmodel.cs
I have a view called empdetails.cshtml and the model i am using for this page is empmodel.cs.
I want to use a property Mobile from contactdetails.cs
Can I use like this in mvc?
#Html.TextBoxFor(m=>m.contactdetails.Mobile)
No. Since you are using empmodel for this view you cannot do it.
What you can you do is create a ViewModel with with contactdetails and empmodel and use that ViewModel in your view.
e.g.
public class EmpViewModel
{
public EmpModel Empmodel { get; set; }
public ContactDetails contactdetails { get; set; }
}
And in your view empdetails.cshtml you can use it as follow;
#model EmpViewModel
#Html.TextBoxFor(m => m.contactdetails.Mobile)
In my asp.net mvc4 app I want to allow users to add multiple regions and cities to their account during the registration. I want to add some subform in which would be the dropdownlist for Region and City and the user should be able to add multiple regions and cities during the registration Process. I know how to do this with jquery but I want to use view model for validation and for creation of this registration form but I do not know how to create this view model and how to define this form in view. I am stating my current registration view model and I want to ask if You can help me to modify it so it will work as I need.
public class RegisterUserModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string Password { get; set; }
[DataType(DataType.Password)]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
Thank you.
You will need to add a collection to your view model that will contain the Regions and Cities. You should create another type to encapsulate these two properties, say Place, so your View Model will look like this:
public class RegisterUserModel
{
// other properties
public List<Place> Places { get; set; }
}
public class Place
{
public string Region { get; set; }
public string City { get; set; }
}
To display the current places in the View Model you simply iterate over them with a foreach and use the helpers to display the Region and City for each one. To add a new Place the key is to name the input correctly so the default Model Binder will treat it as an item in the collection. The default Model Binder uses indexes to do this. For example, the inputs for the first Place in the Places collection should be named like this:
<input name="Places[0].Region" />
<input name="Places[0].City />
The next Place in the collection would be [1] and so on. Since you are familiar with jQuery I will skip how these can be added to the DOM.
I have a controller
public ActionResult UsersInRoles()
{
using (var ctx1 = new UsersModel())
{
var model = new UsersInRolesViewModel();
model.UserProfiles = ctx1.UserProfiles.ToList();
model.UserRoles = ctx1.UserRoles.ToList();
return View(model);
}
}
I am Passing both of those models through to my View:
UserRoles Contains all of my possible roles in the system. Now I need to get an array in my controller of all the roles that a User Is registered for, and pass that through to me view as well, So that I can know not to display roles in a box of available roles which the user is already registered for.
How can I do this?
I see two options:
Some how using linq statement to try and get the data in one go,
or
To pass the full model of roles through and and array of roles that the user is registered for and then I am able to display either or etc in the view?
AUX Classes related to the Usermodel:
public class UsersModel : DbContext
{
public UsersModel()
: base("name=UsersConnection")
{}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<Roles> UserRoles { get; set; }
public DbSet<UsersInRoles> UsersInUserRoles { get; set; }
}
and
public class UsersInRolesViewModel
{
public IList<UserProfile> UserProfiles { get; set; }
public IList<Roles> UserRoles { get; set; }
public IList<ut_GMUTempData> GMUTempData { get; set; }
}
This is a recurring question.
Look at my answer to this SO question: Getting values of check-box from formcollection in asp.net mvc
If that's not clear enough, please, leave a comment.
If you just need roles of the logged in user and you use the default simple membership of Internet Application template, you doesn't need model binding at all. You can retrieve roles of the logged in user in your view like the following:
#{
// r will be a string[] array that contains all roles of the current user.
var r = Roles.GetRolesForUser();
}
and if you want to retrieve roles of any other user, just put the username into that method:
#{
// r will be a string[] array that contains all roles of the entered username.
var r = Roles.GetRolesForUser("username");
}
in this case, you just need to send the username to your model.
Update:
And if you have UserID, you can retrieve username as the following:
#{
SimpleMembershipProvider provider = new SimpleMembershipProvider();
string uname = provider.GetUserNameFromId(id);
// r will be a string[] array that contains all roles of the entered username.
var r = Roles.GetRolesForUser(uname);
}
I have the below model say F:
public partial class F
{
[Key, Display(Name = "Id")]
public int FId { get; set; }
public int RId { get; set; }
public int FTId { get; set; }
public string C { get; set; }
public string U { get; set; }
public string D { get; set; }
[ScaffoldColumn(false)]
public System.DateTimeOffset Created { get; set; }
}
In the controller I have to read all the records of 'F' from database and assign those to an enumerable list of records.
For ex:
ViewBag.Cs = enumerable C column items (textbox)
ViewBag.Us= enumerable U column items (textbox)
ViewBag.FTIDs = enumerable FTId column items (this has to be a dropdown)
In my I have to show
#Html.Textbox(Cs);
#Html.Dropdown(FTIDs);
I gave only textbox and dropdows as an example, there could be many other controls like datetimes, checkboxes etc.,
I should be able to written each column as list a in viewbag and show it in MVC View.
Can somebody advise if this achievable and how?
Many thanks...
Don't use a viewbag for something like this - instead strongly bind your view to a model. Only use a view bag if you have something really small to pass.. anything complex you should always use a strongly typed view model, you get intellisence and its must cleaner for unit testing
View Model:
Public class MyViewModel
{
public List<F> MyListOfFObjects { get; set; }
}
Now when you create your view you can bind it to this view model in the popup or if you don't want to recreate it simply add a reference to it at the top of your view like so:
#model <your project>.<folder view model is in>.<view model name>
for example
#model AdventureWorks.Models.EmployeeViewModel.
In your controller you simply create this view model and pass it to your view such as:
public ActionResult Index()
{
MyViewModel vm = new MyViewModel();
// Initialize your view model
// Get all the F objects from the database and populate the list
return View(vm); // now your view will have the view model
}
Now in the view you can iterate through this view model
#foreach(var fObject in Model)
{
#Html.TextBoxFor(m => m.fId)
#Html.TextBoxFor(m => m.rID)
}
Here is a link to a list of the different #Html helpers that you can use btw
http://qkview.com/techbrij/aspnet-mvc-4
Reference for strongly binded views:
http://www.asp.net/mvc/tutorials/views/dynamic-v-strongly-typed-views