Display User Profile information from Membership .Net using MVC? - asp.net-mvc

I am currently have a bunch of users sitting in a Membership Database and I want to be able to create a page in an MVC App that will be designed to pull back all the user information and display it on the page, I have created the solution below however I want be able to show the data in a Grid View instead of a list:
Controller:
public ActionResult Index()
{
var systemUsers = Membership.GetAllUsers();
return View(systemUsers);
}
View:
<ul>
<%foreach (MembershipUser user in Model){ %>
<li><%=user.UserName %></li>
<% }%>
</ul>
Can someone please tell me how I can get the users data and display it in a Grid View on the View? I was thinking that I could have a model that stores the data in which is then passed to the view and this model could be updated by the controller? But im unsure which datatype could be used to store the users data and then passed to the Grid View?
Thanks :-)

Using MembershipUser directly in your views isn't a very pure MVC approach, IMO.
IMO you could create a specific ViewModel containing just the fields you need to pass between the controller and the view, like so:
public class UserViewModel
{
public Guid UserId {get; set;}
public string UserName {get; set;}
// etc
}
After fetching all your users in your controller, you can then project the MembershipUsers across to your UserViewModel objects, e.g. using LINQ or AutoMapper, and then pass this enumeration into the View.
public ActionResult Index()
{
var systemUsers = Membership.GetAllUsers();
var vmUsers = new List<UserViewModel>();
foreach (MembershipUser u in Membership.GetAllUsers())
{
vmUsers.Add(new UserViewModel()
{
UserId = (Guid)u.ProviderUserKey,
UserName = u.UserName,
// etc
});
}
return View(vmUsers);
}
I'm not sure what you mean by 'GridView' (this is MVC, not WebForms), but the MVC WebGrid should do fine:
#model IEnumerable<MyNamespace.UserViewModel>
#{
var grid = new WebGrid(Model);
}
<div id="grid">
#grid.GetHtml()
</div>
Obviously you'll want to tweak the look and feel a bit.

Related

Queries realted to Dropdown list in MVC

I am a new to ASP.NET MVC, I am developing an application. I want to bind the data in the drop down list in create view.
How to bind the data in the drop down? I have go through many question and answers here...
I have seen usually everyone suggested to use List<SelectListItem> what is its purpose?
Do I need to use ViewModel while binding the data to drop down list?
Can I get simple example where data get bind in the dropdown using viewbag?
I have created a list in controller
List<string> items = new List<string>();
and I want to pass this list to view using viewbag and simply want to bind to drop down list.
How to do this ?
I'd suggest using a ViewModel as it makes interaction with user input so much easier. Here's an example of how you might bind data from your ViewModel to a drop down in your View. First, the ViewModel:
public class CrowdViewModel
{
public string SelectedPerson { get; set;}
public IEnumerable<SelectListItem> People { get; set; }
}
So yes, you're right - use a collection of SelectListItems. I'm guessing in your case, the SelectListItem's Value and Text property will be the same. You could turn your List into IEnumerable like this:
[HttpGet]
public ActionResult Home()
{
// get your list of strings somehow
// ...
var viewModel = new CrowdViewModel
{
People = items.Select(x => new SelectListItem { Text = x, Value = x })
}
return View(viewModel);
}
Now you need to bind that ViewModel's property to the DropDown on your view. If you're using the Razor ViewEngine, the code will look something like this:
#model MyApp.ViewModels.CrowdViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.SelectedPerson, Model.People)
}
Now when you post that form, MVC will bind the selected value to the ViewModel's SelectedPerson property!
[HttpPost]
public ActionResult Home(CrowdViewModel viewModel)
{
// viewModel.SelectedPerson == whatever the user selected
// ...
}
Easy as that!
Update:
If you really want to use the ViewBag (don't do it), you can pass your list through from your Controller action like so:
[HttpGet]
public ActionResult Home()
{
ViewBag.People = new List<string> { "Bob", "Harry", "John" };
return View();
}
And then create a SelectList on your View:
#Html.DropDownList("SelectedPerson", new SelectList(ViewBag.People, Model))

ASP.NET MVC - drop down list selection - partial views and model binding

I'm fairly new to ASP.NET MVC and am trying to work out the best way to do this. It's probably simple but I just want to do things correctly so I thought I'd ask.
Lets say I have a model that is this:
Task - Id, Description, AssignedStaffMember
StaffMember - Id, FirstName, LastName
and in my view I want to create a new task. I make a strongly typed Razor view, and can use EditorFor to create textboxes for Description but what about AssignedStaffMember?
I want a drop down list of all current staff and have the option of selecting one, then this gets submitted to an action method which is
NewTask(string description, StaffMember assignedStaffMember)
either that or I could have an int for staffId instead of the StaffMember object and look it up in the action method.
What is the best way to do this? I need to go to the database to get the list off staff, so here's what I thought:
Make a partial view for the listing of staff drop down, which will be used a few times and use #Html.Action("ListStaff", "Staff") to call it. The action method then has
public ActionResult ListStaff()
{
IEnumerable<StaffMember> model = _serviceLayer.GetAllStaff();
return PartialView(model);
}
However I'm not sure on how this will work with model binding, my understanding is that it has to have the correct name for the form to submit it, I'd need to pass the name to the partial view to put on the element I guess?
Instead of having it call a controller to get the staff, make a ViewModel that contains my Task and a IEnumerable possibleStaff collection. possibly send this information to a partial view.
a Html Helper ?
EditorFor could somehow be used?
which one (or is there more) would be best? and how would I do the model binding?
Here is one way to do this. Create a TaskDetailsViewModel
public class TaskDetailsViewModel
{
public TaskDetailsViewModel()
{
this.Task = new Task();
this.StaffMembers = new List<StaffMember>();
}
public Task Task { get; set; }
public IEnumerable<StaffMember> StaffMembers { get; set; }
}
In Controller
public ActionResult Edit(int id)
{
var task = taskRepository.GetTaskByID(id);
var taskDetailsViewModel = new TaskDetailsViewModel();
// Populate taskDetailsViewModel from task and staff
return View(taskDetailsViewModel);
}
[HttpPost]
public ActionResult Edit(TaskDetailsViewModel taskDetailsViewModel)
{
if (ModelState.IsValid)
{
taskRepository.Save(taskDetailsViewModel.Task);
}
else
{
// Show Error
}
return View(taskDetailsViewModel);
}
In View (bound strongly to TaskDetailsViewModel)
#Html.DropDownListFor(model => model.Task.AssignedStaffMember, new SelectList(Model.StaffMembers, "ID", "FirstName", Model.Task.AssignedStaffMember))
#Html.ValidationMessageFor(model => model.Task.AssignedStaffMember)

General .NET MVC2 questions

I am just getting into .NET MVC2 (.NET in general even) and I am having a hard time getting familiar with the "flow" of things. The MVC framework, I get.. for the most part. The part that I am getting tripped up on is applying standard programming practices to .NET MVC.
For example
public ActionResult Index()
{
var dataContext = new SiteContentDataContext();
var data = from c in dataContext.SiteContents where c.Slug == "home-page" select c;
// call/return getMainNav()
// call/return getSubNav()
return View(data);
}
public ActionResult SiteContent(string strSlug)
{
var dataContext = new SiteContentDataContext();
var data = from c in dataContext.SiteContents where c.Slug == strSlug select c;
// call/return getMainNav()
// call/return getSubNav()
return View(data);
}
private void getSubNav()
{
// get subnav records from db.
// return subnav records.
}
private void getMainNav()
{
// get main nav records from db.
// return main nav records.
}
The Index and SiteContent view are identical except for the fact that the Index view uses a different master page. Both views have a subnav and a main nav that will be dynamic content from a database.
The question, finally, is how would I go about populating the getSubNav and getMainNav functions and second, how would I return that data to the view properly?
Look into ViewModel objects, objects you create whose purpose in life is to carry data to and from your Views. The Models folder created for you by default in a new MVC project would hold exactly those classes.
You have options besides the ViewModel object methodology, but none are as clean. (The ViewData dictionary is around to help but it's not intended to be the primary means of providing data to your views.) Here's an example of how to set the Model property of the ViewData object to an instantiated, populated viewmodel instance:
public ActionResult SiteContent(string strSlug) {
SiteContentVM model = new SiteContentVM();
SiteService siteService = new SiteService();
model.Slug = siteService.GetALittleSlimyCreature(strSlug);
model.List1 = siteService.GetList1();
model.List2 = siteService.GetList2();
ViewData.Model = model;
return View();
}
You can now create a strongly typed view (complete with intellisense) to reference any properties of your ViewModel object instance from within your view simply through the Model property:
<% foreach (var item in Model.List1) { %>
<% Html.Encode(item.StringField) %> <!-- <= writing a property -->
<% Html.RenderPartial("PartialNameHere", item); %> <!-- <= the equivalent of a usercontrol -->
<% } %>
As you see above the process of getting data from the database does not change for MVC. You do it just as you would in a normal webforms project. (...usually this involves instantiating a business logic or service class of some sort rather than actually writing the code in the MVC project.)
Enjoy MVC!
You should look into DDD and TDD for ASP.NET MVC. For the looks of it you seem to be using Linq To Sql. I'm going to try to explain in a few words what I do to accomplish a good architecture.
Architecture
DB Context
Domain Model
Repository Pattern
It's good practice not to tie your Database Context with your Controllers. What you want to do is have your Controllers call your Repository, which in turn will return your Model. Now here's the tricky part you must convert the DB Context Objects into your Model Objects.
Imagine you have an Products table which Linq To SQL will give you as the Products Class.
That Products Class is part of the DB Context and what you want to do is alienate your context, in fact your Controllers won't even know it exists.
Why would I need a Model when I have Linq To SQL?
Well for starters LTS will regenerate all Objects everytime you change your Database meaning you wont have the ability to make change to the DB Context. And also you want to be able to use ASP.NET MVC 2 Annotations for validation and more.
Now create a Products Class for your Model
namespace MvcApplication.Models
{
public class Product
{
public int Id { get; set; }
[Required]
[StringLength(10)]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[DisplayName("Price")]
[Required]
[RegularExpression(#"^\$?\d+(\.(\d{2}))?$")]
public decimal UnitPrice { get; set; }
}
}
Now you see this Class is part of the Model totally disconnected from the DB Context. Now what we do next is create our Repository Class.
namespace MvcApplication.Repository
{
public class AppRepository {
DbContext _context = new DbContext();
public IQueryable<Products> GetProducts()
{
return from p in _context.Products
select new Product {
Name = p.Name,
UnitPrice = p.UnitPrice
}
}
}
}
Now in your Controller you just call GetProducts();
public ActionResult SiteContent(string strSlug)
{
var repository = new AppRepository();
return View(repository.GetProducts());
}
Pretty isn't it.
You can use AutoMapper to map your DB Context objects to your Model objects.
http://automapper.codeplex.com/
Well ,,, i think what you are looking for here is Partial Views.
You can embed the MainNav & SubNav Views into your SiteContent View.
here's how this goes.
create your MainNav & SubNav as partial views.
in your SiteContent view use the Html.RendarPartial Method to include the other two views.
<%= Html.RenderPartial("MainNav", Model); %>
<%= Html.RenderPartial("SubNav", Model); %>
Now to the remaining part about how to get the data to the MainNav & SubNav views. Now is a good time to get familiar with ViewModels. View models are nothing but classes with some properties that you want to give to a view to display.
In your case i would create 3 view models.
SiteContentViewModel contains the content that will be displayed in your page.
MainNavViewModel contains the data that will be displayed insdie the MainNav.
SubNavVIewModel contains the data that will be displayed insdie the SubNav.
then i would include the MainNavViewModel & SubNavVIewModel inside the SiteContentViewModel.
(if you are sure that every SiteContent View will have a MainNav & a SubNav )
Now it's up to you to fill each view model with that data that you need.
here's how the code will look like.
public class SiteContentViewModel {
public MainNavViewModel MainNav { get; set;}
public SubNavVIewModel SubNav { get; set;}
// Any Other Data Needed In The SiteContent View (ex. PageTitle)
}
public class MainNavViewModel {
// Any Data Needed In The MainNav View
}
public class SubNavVIewModel {
// Any Data Needed In The SubNav View
}
Now back to the Partial Views ,,, using the View Models we created we can include the partials like this.
<%= Html.RenderPartial("MainNav", Model.MainNav); %>
<%= Html.RenderPartial("SubNav", Model.SubNav); %>
one important thing is to make our views strongly typed.
SiteContent view of type SiteContentViewModel
MainNav view of type MainNavViewModel
SubNav vIew of type SubNavViewModel
and in your SiteContent action method you will do something like this
// Initialize the ViewModels.
SiteContentViewModel model = new SiteContentViewModel();
model.MainNav = new MainNavViewModel();
model.SubNav = new SubNavVIewModel();
// Get Data From DB and set the properties that you created in your view models.
// examples.
model.PageTitle = // some data from db.
model.MainNav.(Some Property) = // some data from db.
model.SubNav.(Some Property ) = // some data from db.
return View(model);
hope that helps ... for more information you can see this link

GetAllUsers - MVC

I’m using the Membership Provider and would like to display a list of all the users and their First Name, Last Name etc using the GetAllUsers function.
I'm having trouble understanding how to implement this function in MVC.
Has anyone implemented this in MVC or is there an easier way to list all the users in my application?
Any help or advise would be really helpful.
Controller
public ActionResult GetUsers()
{
var users = Membership.GetAllUsers();
return View(users);
}
View Model
public class GetUsers
{
[Required]
[DisplayName("User name")]
public string UserName { get; set; }
[Required]
[DisplayName("User name")]
public string FirstName { get; set; }
}
View
<%= Html.Encode(item.UserName) %>
Error
The model item passed into the dictionary is of type 'System.Web.Security.MembershipUserCollection', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Account.Models.GetUsers]'.
View
Inherits="System.Web.Mvc.ViewPage<MembershipUserCollection>"
<ul>
<%foreach (MembershipUser user in Model){ %>
<li><%=user.UserName %></li>
<% }%>
</ul>
Controller
public ActionResult Admin()
{
var users = Membership.GetAllUsers();
return View(users);
}
What's the difficulty you have with it? the GetAllUsers method simply returns a collection of users that you can then display ... either manually, or using a grid component from a vendor like Telerik.
something like:
<% foreach(var user in Membership.GetAllUsers()) { %>
<p>Name: <%= user.UserName %></p>
<% } %>
Obviously, heed the warning in the documentation:
Be careful when using the GetAllUsers
method with very large user databases,
as the resulting
MembershipUserCollection in your
ASP.NET page may degrade the
performance of your application.
There is an overload which lets you do paging to get around this :-)
#Jemes, the problem you're having is that you're passing a System.Web.Security.MembershipUserCollection as the model to your view and you specified that the model of your view was of type Account.Models.GetUsers. Change the type to System.Web.Security.MembershipUserCollection. However, if you're using the default Membership provider in your solution, you will not have the First Name available as the MembershipUser class doesn't have a FirstName property.

passing parameters to my partial view?

I am calling my partial view like this:
<% Html.RenderPartial("~/controls/users.ascx"); %>
Can I pass parameters to partial view? How will I access them in the actual users.ascx page?
You could pass a model object to the partial (for example a list of strings):
<% Html.RenderPartial("~/controls/users.ascx", new string[] { "foo", "bar" }); %>
Then you strongly type the partial and the Model property will be of the appropriate type:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Collections.Generic.IEnumerable<string>>" %>
<% foreach (var item in Model) { %>
<div><%= Html.Encode(item) %></div>
<% } %>
There is another overload for RenderPartial that will pass your model through.
<% Html.RenderPartial("~/controls/users.ascx", modelGoesHere); %>
How to access? Just like you normally would with any view:
<%= Model.MagicSauce %>
It took a while to sink in, but MVC means you use a Model, a View, and a Controller one way or another for just about everything, including Partial Views. How all three elements fit together can be a little intimidating at first. I'd never done one until just now, and it works --Woohoo!
Hope this helps the next person.... Sorry, I'm using razor instead of .Net forms. I'm also pulling data from a SQL Server database into Entity Framework, which a developer is likely to use. I also probably went a little overboard with WebGrid, which is so much more elegant than a foreach statement. A basic #webgrid.GetHtml() will display every column and row.
Background
In this working example, users have uploaded pictures. Their pictures are displayed in their edit form using a partial view. The ImageID and FileName metadata is persisted in SQL Server while the file itself is persisted in the ~/Content/UserPictures directory.
I know it's kinda half vast, because all the details of uploading and editing personal data isn't shown. Just the germane parts of using a Partial View are focused on, albeit with some bonus EF thrown in. The namespace is MVCApp3 for S&G.
Partial View Model ViewModels.cs
The SQL Server Images table includes many more columns in addition to ImageID and FileName such as [Caption], [Description], a MD5 hash to prevent the same image being uploaded multiple times, and upload date. The ViewModel distills the Entity down to the bare minimum needed for a user to see their pictures.
public class Picts
{
public int ImageID { get; set; }
public string FileName { get; set; }
}
Main View View Edit.cshtml
Note the cast/convert to strongly type the ViewData[].
#Html.Partial(
partialViewName: "Picts",
model: (IEnumerable<MVCApp3.Models.Picts>)ViewData["Picts"]
)
If you don't set the strongly-typed model to use for the Partial View you'll get a "The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies..." error because it assumes you're passing the parent/master model.
Partial View View Picts.cshtml (the whole file contents is shown)
#model IEnumerable<MVCApp3.Models.Picts>
#{
var pictsgrid = new WebGrid(Model);
}
#pictsgrid.GetHtml(
tableStyle: "grid",
displayHeader: false,
alternatingRowStyle: "alt",
columns: pictsgrid.Columns(
pictsgrid.Column(format:#<text><img src="#Url.Content("~/Content/Users/" + #item.FileName)" alt="#item.ImageID" width="200" />
#Html.ActionLink(linkText: "Delete", actionName: "DeletePicture", routeValues: new { id = #item.ImageID })
</text>)
))
Controller IdentityController.cs
Set the data content into the ViewData["MyPartialViewModelKeyName"] your partial view will consume. You can give the dictionary key any name you want, but I gave it ViewData["Picts"] to be consistent with the partial view file name and its view model class definition.
Because the pictures may be shared amongst multiple users there is a many-to-many table with a corresponding PITA query in Entity Framework using nested froms and inner joins to return just the pictures belonging to, or shared with, a user:
public class IdentityController : Controller
{
private EzPL8Entities db = new EzPL8Entities();
// GET: /Identity/Edit/5
[Authorize]
public ActionResult Edit(int? id)
{
if (id == null)
return new HttpNotFoundResult("This doesn't exist");
// get main form data
ezpl8_UsersPhysicalIdentity ezIDobj = db.ezpl8_UsersPhysicalIdentity.Find(id)
// http://learnentityframework.com/LearnEntityFramework/tutorials/many-to-many-relationships-in-the-entity-data-model/
// get partial form data for just this user's pictures
ViewData["Picts"] = (from user in db.ezpl8_Users
from ui in user.ezpl8_Images
join image in db.ezpl8_Images
on ui.ImageID equals image.ImageID
where user.ezpl8_UserID == id
select new Picts
{
FileName = image.FileName,
ImageID = image.ImageID
}
).ToList();
return View(ezIDobj);
}
// Here's the Partial View Controller --not much to it!
public ViewResult Picts(int id)
{
return View(ViewData["Picts"]);
}
[Authorize] //you have to at least be logged on
public ActionResult DeletePicture(int id)
{
//ToDo: better security so a user can't delete another user's picture
// TempData["ezpl8_UserID"]
ezpl8_Images i = db.ezpl8_Images.Find(id);
if (i != null)
{
var path = System.IO.Path.Combine(Server.MapPath("~/Content/Users"), i.FileName);
System.IO.File.Delete(path: path);
db.ezpl8_Images.Remove(i);
db.SaveChanges();
}
return Redirect(Request.UrlReferrer.ToString());
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
// get main form data
ezpl8_UsersPhysicalIdentity ezIDobj = db.ezpl8_UsersPhysicalIdentity.Find(id)
// http://learnentityframework.com/LearnEntityFramework/tutorials/many-to-many-relationships-in-the-entity-data-model/
// get partial form data for just this user's pictures
ViewData["Picts"] = (from user in db.ezpl8_Users
from ui in user.ezpl8_Images
join image in db.ezpl8_Images
on ui.ImageID equals image.ImageID
where user.ezpl8_UserID == id
select new Picts
{
FileName = image.FileName,
ImageID = image.ImageID
}
).ToList();
return View(ezIDobj);
}
// Here's the Partial View Controller --not much to it!
public ViewResult Picts(int id)
{
return View(ViewData["Picts"]);
}
[Authorize] //you have to at least be logged on
public ActionResult DeletePicture(int id)
{
//ToDo: better security so a user can't delete another user's picture
// TempData["ezpl8_UserID"]
ezpl8_Images i = db.ezpl8_Images.Find(id);
if (i != null)
{
var path = System.IO.Path.Combine(Server.MapPath("~/Content/Users"), i.FileName);
System.IO.File.Delete(path: path);
db.ezpl8_Images.Remove(i);
db.SaveChanges();
}
return Redirect(Request.UrlReferrer.ToString());
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}

Resources