How to print after join linq query - c#

I have this code:
public ActionResult Index()
{
MembershipUser currentUser = Membership.GetUser();
Guid UserId = (Guid)currentUser.ProviderUserKey;
var users = from m in db.Users
join m2 in db.MyProfiles on m.UserId equals m2.UserId
where m.UserId == UserId
select new{UserName = m.UserName, LastActivityDate = m.LastActivityDate,
Address = m2.Address, City = m2.City, State = m2.State, Zip = m2.Zip};
return View(users);
}
This code is in my Controller, I want to run this query and then print the results into my view, how would I write the view?

//if your question is how to display(Print!) a view for above query then in ActionResult Index()
//1] As as best practise always Create a ViewModel - UserViewModel
public class UserviewModel
{
public string Username {get;set;}
public string Address {get;set;}
}
//2] Assign db.user values to UserviewModel or you can use Automapper
//and 3] then return this viewmodel to view
return View(UserviewModel);

This code cannot work because your LINQ query is returning an anonymous object so you cannot strongly type your view. So the first step would be to define a view model which will represent the information you are willing to display on your view:
public class UserViewModel
{
public string UserName { get; set; }
public DateTime LastActivityDate { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
then in your controller action you would return a collection of this view model:
public ActionResult Index()
{
var currentUser = Membership.GetUser();
var userId = (Guid)currentUser.ProviderUserKey;
var users =
from m in db.Users
join m2 in db.MyProfiles on m.UserId equals m2.UserId
where m.UserId == userId
select new UserViewModel
{
UserName = m.UserName,
LastActivityDate = m.LastActivityDate,
Address = m2.Address,
City = m2.City,
State = m2.State,
Zip = m2.Zip
};
return View(users);
}
and finally in your strongly typed view:
#model IEnumerable<AppName.Models.UserViewModel>
#Html.DisplayForModel()
and in the corresponding display template (~/Views/Shared/DisplayTemplates/UserViewModel.cshtml) which will be rendered for each item of the collection:
#model AppName.Models.UserViewModel
<div>
Username: #Html.DisplayFor(x => x.UserName)<br/>
Last activity: #Html.DisplayFor(x => x.LastActivityDate)<br/>
...
</div>

You need to get the type of users and make a List-View of that type. Easiest way to make a view is simply right-clicking in your controller method and selecting Create View. That'll make sure the routing gets done properly as well.

Related

MVC5/C#: Pass LINQ inner Join query to view model

i'm trying to pass data(.tolist) in inner join query to viewmodel, to use these data in view that contain also a partial view that needs data from viewModel.
public ActionResult IndexAdmin()
{
int userId = (int)Session["UserID"];
userInfo = _context.UserInfo.Find(userId);
var AllTours= (from p in _context.PostsInfo //Why this doesn't return two records
join r in _context.Region
on p.RegionId equals r.Id
where r.CountryId == 1
select new
{
RegionName = r.CountryId,
ImageName = p.ImageName,
}).Distinct().ToList();
//Here i need to define IndexAdminViewModel to populate tours and userInfo.username
return View(AllTours);
}
This is the IndexAdminViewModel:
public class IndexAdminViewModel
{
public string UserName { get; set; }
public string RegionName{get;set;}
public string ImageName {get;set;}
}
The view(IndexAdmin.cshtml)
#Html.Partial("_BarPartialAdmin", Model)
foreach (var post in Model)
{
<img src="~/images/#post.ImageName" alt="QfirstImage">
<h2>post.RegionName</h2>
}
The partial view will only needs the username to display it for once so i used to pass the model to partial view in order to use the username property, the RegionName and ImageName is a collection so that i can iterate over them and get teh values some way like use them in a table.
My question is how to pass the inner join query results AND theuserinfo.username to viewModel to use them in the view???????
You need to create 2 view models
public class ToursViewModel
{
public string RegionName { get; set; }
public string ImageName {get; set; }
}
public class IndexAdminViewModel
{
public string UserName { get; set; }
public IEnumerable<ToursViewModel> Tours {get;set;}
}
Then in the controller
public ActionResult IndexAdmin()
{
int userId = (int)Session["UserID"];
userInfo = _context.UserInfo.Find(userId);
IEnumerable<ToursViewModel> tours = (
from p in _context.PostsInfo
join r in _context.Region
on p.RegionId equals r.Id
where r.CountryId == 1
select new ToursViewModel
{
RegionName = r.CountryId,
ImageName = p.ImageName
});
IndexAdminViewModel model = new IndexAdminViewModel
{
UserName = userInfo.username,
Tours = tours
};
return View(model);
and in the view
#model IndexAdminViewModel
....
<h1>#Model.UserName</h1>
#foreach (var tour in Model.Tours)
{
<img src="~/images/#tour.ImageName" alt="QfirstImage">
<h2>#tour.RegionName</h2>
}
I you need to pass different objects to the view you basically have two options:
Create a composite class and use that as model
var allTours=
from p in _context.PostsInfo //Why this doesn't return two records
join r in _context.Region
on p.RegionId equals r.Id
where r.CountryId == 1
select new PostAndRegion
{
Region = r.CountryId,
Post= p.ImageName,
};
var model = new MyCompositeModel
{
PostsAndRegions = allTours.ToArray(),
UserInfo = null // or get from where you want to
};
return View(model);
with
public class PostAndRegion
{
public Post Post{get;set;}
public Region Region {get;set;}
}
public class MyCompositeModel
{
public IList<PostAndRegion> PostsAndRegions{get;set;}
public UserInfo MyUserInfo{get;set;}
}
Put some of the data in the ViewBag. see http://www.tutorialsteacher.com/mvc/viewbag-in-asp.net-mvc

List View displaying Roles and Application User

I am very new to MVC5 and am trying to display a List view of user details and the name of the role they are in. I have set up the roles using MVC Identity.
Below is my ViewModel
public class UserRoleViewModel
{
public string UserRoleVMId { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Role { get; set; }
public bool AccountEnabled { get; set; }
}
And my controller:
public ActionResult Index()
{
var model = (from d in db.Users
select new UserRoleViewModel()
{
UserRoleVMId = d.Id,
Title = d.Title,
FirstName = d.FirstName,
Surname = d.Surname,
Email = d.Email,
AccountEnabled = d.AccountEnabled,
Role = d.Role.Name
}).ToList();
return View(model);
}
I am unsure of how to display the role name and am getting the error message
does not contain the definition for Role and no extension method Role
at
Role = d.Role.Name
Any help would be greatly appreciated
Thanks
You can use the GetRoles method :
viewModel.RolesForThisUser = UserManager.GetRoles(userId).ToList();
This is useful when you want to display the details of one user.
You should use The property Roles, since a user could have multiple roles:
public ActionResult Index()
{
using(var context = new IdentityDbContext()){
viewModel =
context.Users
.Include("Roles")
.Select(u =>
new UserRoleViewModel {
UserRoleVMId = u.Id,
Title = u.Title,
FirstName = u.FirstName,
Surname = u.Surname,
Email = u.Email,
AccountEnabled = u.AccountEnabled,
Role = u.Roles.First().Role.ToString()
}
).ToList();
}
return View(viewModel);
}
You can use this code
return view(db.Users.ToList());
and in your view on top use
#model IEnumerable<YourProjectName.Models.Users>
and use this foreach for show content
#foreach(var item in Model){<p>#item.Title</p> and etc }

MVC 5 MultiSelectList Selected Values Not Working

I have a ListBox in a View displaying the possible choices. However, the user's role(s) are not shown as selected. In my UserViewModel the Roles collection contains the complete list of roles, and AspNetRoles collection contains only the roles to which the user belongs. I've tried multiple examples/variations but nothing ever shows as selected. I'm stuck.
ViewModel:
public class UserViewModel
{
public string Id { get; set; }
public string Email { get; set; }
public ICollection<AspNetRole> Roles { get; set; }
public virtual ICollection<AspNetRole> AspNetRoles { get; set; }
}
Controller:
public ActionResult Edit(string id)
{
UserViewModel user = new UserViewModel();
AspNetUser aspNetUser = new AspNetUser();
if (!string.IsNullOrEmpty(id))
{
aspNetUser = db.AspNetUsers.Find(id);
user.Id = aspNetUser.Id;
user.Email = aspNetUser.Email;
user.AspNetRoles = aspNetUser.AspNetRoles;
var roles = (from r in db.AspNetRoles
select r).ToList();
user.Roles = roles;
}
return View(user);
}
View:
#Html.ListBox("AspNetRoles",
new MultiSelectList(Model.Roles, "Id", "Name",
Model.AspNetRoles.Select(m => m.Id)))
You have not posted your model, but it appears that property AspNetRoles is a collection of a complex object (you cannot bind to a complex object, only a value type - or in the case of ListBox, a collection of value type). You can handle this by changing AspNetRoles to int[] (assuming the ID property of Role is int)
#Html.ListBoxFor(m => m.AspNetRoles, new SelectList(Model.Roles, "Id", "Name"))
Note, Its always better to use the strongly typed helpers.

Displaying multiple tables from model in single view

I have two tables TxtComment and Login.
I am displaying image urls from Login table and comments from TxtComment table where username in TxtComment equals username in Login.
I am using Db First approach using entityframework.
How can I concatenate these columns from different tables to one common view? I used ViewBag. I got a result.
Controller
public ActionResult Item(int id)
{
FoodContext db = new FoodContext();
ViewBag.FoodItems = db.FoodItems.Where(row => row.itemid == id);
ViewBag.TxtComments = (from user in db.TxtComments
from ff in db.Logins
where ff.username == user.username
select new { imgurl = ff.imgurl, txtcmt = user.txtcmt });
return View();
}
View
#for(var item in ViewBag.TxtComments)
{
<div>#item</div>
}
The result is {imgurl=http:/sdfsdf,txtcmt=sfsdfsdf}
I need each item seperate. How can I? I tried with #item.imgurl, it says error. Is view bag is better? If not, please help me this need with strongly type view.
Create your own ViewModel instead of putting the model inside the ViewBag.
ViewModel:
public class ViewModel
{
public List<ImageComment> ImageComments { get; set; }
public ViewModel()
{
ImageComments = new List<ImageComment>();
}
}
public class ImageComment
{
public string ImageUrl { get; set; }
public string Comment { get; set; }
}
Controller Action:
public ViewResult Item(int id)
{
FoodContext db = new FoodContext();
List<ImageComment> comments = (from user in db.TxtComments
from ff in db.Logins
where ff.username == user.username
select new ImageComment
{
ImageUrl = ff.imgurl,
Comment = user.txtcmt
}).ToList();
ViewModel vm = new ViewModel{ ImageComments = comments };
return View("MyView", vm);
}
View:
#model ViewModel
#{
ViewBag.Title = "Comments";
}
#foreach(ImageComment comment in Model.ImageComments)
{
<p>#comment.Comment</p>
<img src="#comment.ImageUrl" alt="img" />
}

Dropdown list - MVC3

I am using C# in ASP MVC3. I have two tables from SQL Server.Table names are SMS_User and SMS_Division in SQL Server 2008. When i create a new user, I want to show division id from sms_division table.
SMS_User contains UserName, DivisionID, EmailAddress
SMS_Division contains DivisionID, DivisionName.
Controller Code :
UserController : Controller
{
private NetPerfMonEntities2 db = new NetPerfMonEntities2();
IEnumerableZamZam= db.SMS_Division.Select(c => new SelectListItem { Value = c.divisionid.ToString(), Text = c.divisionid.ToString() } );
}
When I create a new user in User Create() VIEW I want to show a DivisonName as a dropdown list instead of a text box. How I do that ?
#Html.DropDownListFor(model => model.divisionid, (IEnumerable<SelectListItem>) ViewData["Divisions"], "<--Select a divison-->")
#Html.ValidationMessageFor(model => model.divisionid)
I have this error message :
CS0103: The name 'sms_amountlimit2' does not exist in the current context
I'll be assuming a few missing part of your question in my answer, and give you a generic pattern to have a working dropdown list in ASP.NET MVC 3 :
Let's start with the models :
UserModel would be the class representing the data extracted from sms_user
public class UserModel
{
public string Username { get; set; }
public string EmailAddress { get; set; }
public int DivisionId { get; set; }
}
DivisionModel would be the class representing the data extracted from sms_division
public class DivisionModel
{
public int DivisionId { get; set; }
public string DivisionName { get; set; }
}
By Extracted, I mean anything that can transform the data in your Database in instanciated classes. That can be an ORM (EntityFramework or others), or SQL Queries, etc...
Next, is the viewmodel, because it wouldn't make sense to plug an IEnumerable of divisions in UserModel, and I personally don't really like using ViewData when I can avoid it :
public class UserViewModel
{
public UserModel User { get; set; }
public IEnumerable<DivisionModel> Divisions {get; set;}
}
Next, the controller :
public class UserController : Controller
{
public ActionResult Create()
{
List<DivisionModel> divisions = new List<DivisionModel>();
divisions.Add(new DivisionModel() { DivisionId = 1, DivisionName = "Division1" });
divisions.Add(new DivisionModel() { DivisionId = 2, DivisionName = "Division2" });
UserModel user = new UserModel() { Username = "testUser", EmailAddress = "testAddress#test.com" };
return View(new UserViewModel() { User = user, Divisions = divisions });
}
}
I just create the Division list and the user, but you would get then from you database by any means you are using.
And finally the View :
#model ViewModels.UserViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<p>
#Html.DropDownListFor(model => model.User.DivisionId, new SelectList(Model.Divisions, "DivisionId", "DivisionName"), "-- Select Division --")
#Html.ValidationMessageFor(model => model.User.DivisionId)
</p>
Note that the model binded to the view is the ViewModel.
In your model add a collection of the divisions then create the dropdown list like below:
#Html.DropDownListFor(m => m.SelectedDivisionId,
new SelectList(Model.Divisions, "DivisionId", "DivisionName"),
"-- Select Division --")

Categories