Retrieve data of Logged in user from other table through LINQ - asp.net

This is my ViewModel where i've added two of my tables. Account_Detail (im getting login from this table). Basic_Detail (I need to retrieve data from this table after user logs in, through Session)
public class BasicAccountView
{
public Account_Details Account_Details { get; set; }
public Basic_Details Basic_Details { get; set; }
}
Here is my login code, I've got both Name and ID in their respective Session variables
public ActionResult Index(Account_Details log)
{
var obj = db.Account_Details.Where(u => u.Name.Equals(log.Name) && u.Password.Equals(log.Password)).FirstOrDefault();
Session["Account"] = log;
if (obj != null)
{
Session["loginid"] = obj.U_ID;
Session["name"] = obj.Name;
Session["email"] = obj.Email;
return RedirectToAction("Verify");
}
else
{
return View();
}
}
Login code is all okay and get going, even Session is working fine, they're retrieving Name of logged in user. Though, scenario is like, I need to join this Account and Basic table, so that I can get details of logged in user from Basic_Detail table. here is my join query, but it ain't working, showing nothing at all.
public ActionResult Verify()
{
var Result = (from o in db.Basic_Details
join od in db.Account_Details on o.User_ID equals od.U_ID
where o.FirstName == this.HttpContext.User.Identity.Name
select new BasicAccountView { Basic_Details = o, Account_Details = od }).ToList();
//var Result = (from o in db.Basic_Details
// join od in db.Account_Details on o.User_ID equals od.U_ID
// select new Basic_Details { FirstName = od.Name }).ToList();
return View(Result);
}
View of Verify Action
#model IEnumerable<Matrimonial.Models.BasicAccountView>
#{
ViewBag.Title = "Verify";
Layout = "~/Views/Shared/Main.cshtml";
}
<p>
#Html.ActionLink("Create New", "Create")
</p>
#foreach(var item in Model)
{
<td>#item.Basic_Details.FirstName</td>
<td>#item.Basic_Details.LastName</td>
<td>#item.Basic_Details.MaritalStatus</td>
<td>#item.Basic_Details.Religion</td>
}
UPDATE - ISSUE RESOLVED
Just get Session["loginid"] into other variable and compare it to other table UserID from where you want to retrieve the data. I hope it'll help others with the same issue.
public ActionResult Verify()
{
BasicAccountView bav = new BasicAccountView();
int userId = (int)Session["loginid"];
var Result = from o in db.Basic_Details
join od in db.Account_Details on o.User_ID equals od.U_ID
where o.User_ID == userId
select new BasicAccountView { Basic_Details = o, Account_Details = od };
//var Result = (from o in db.Basic_Details
// join od in db.Account_Details on o.User_ID equals od.U_ID
// select new Basic_Details { FirstName = od.Name }).ToList();
return View(Result);
}

You should check the actual value of "this.HttpContext.User.Identity.Name", it may be the problem.
Furthermore, check whether the JOIN query returns any results (exclude the WHERE clause).
I hope it gave you a clue.

Related

I have an Asp.net mvc project with Individual User Accounts. I want each user just see own data created before in index method in controller

public class OrderController : Controller
{
private PurcasementEntities db = new PurcasementEntities();
// GET: Order
public ActionResult Index(string Dep, string searchString)
{
var DepLst = new List<string>();
var DepQry = from d in db.Orders
orderby d.Department
select d.Department;
DepLst.AddRange(DepQry.Distinct());
ViewBag.Dep = new SelectList(DepLst);
var ord = from m in db.Orders
select m;
if (!String.IsNullOrEmpty(searchString))
{
ord = ord.Where(s => s.Description.Contains(searchString));
}
if (!string.IsNullOrEmpty(Dep))
{
ord = ord.Where(x => x.Department == Dep);
}
return View(ord);
}
}
For login what kind of authentication you are using?
Hope it's identity server.
Then you can get the logged in user ID by the code '''User.Identity.Name'''. Just filter your database record by using the where clause in your query like "'where userID = User.Identity.Name"'
Hope this helps.

Convert IQueryable object to a List and add a new Item

I have the following IQueryable object:
var user = from d in _context.Users
join userRole in _context.UserRoles on d.Id equals userRole.UserId
join role in _context.Roles on userRole.RoleId equals role.Id
where role.Name == "Liquidador"
select d;
Which then is send as a ViewBag to the View:
ViewBag.UserID = new SelectList(user.AsNoTracking(), "UserName", "Name", selectedUser);
The Problem:
I need to add a new Item to the result of the IQueryable. So I've proceeded like this:
var UserNameList = user.Select(s => new { s.Name, s.UserName }).ToList();
However, I'm missing something when I'm trying to add the new item:
UserNameList.Insert(0, new *NewWhat?* { Name = "Liquidador", UserName = "--Select--"} );
Usually I declare a new element of a specific model but in this case I don't know which model to declare for this IQueryable. Any recomendations?
Thanks
EDIT:
The IQueryable object goes to the Get Method of the View as part of a function:
public async Task<IActionResult> Management()
{
PopulateUserDropDownList();
var Tiendas = await _context.Stores.ToListAsync();
StoreEmployee model = new StoreEmployee
{
Stores = Tiendas
};
return View(model);
}
This list is then presented in a dropdownlist, inside a table:
<td class="col-md-2">
<div class="form-group" form="#(String.Format("{0}{1}","form",item.StoreID))">
<div>
<select asp-for="#item.Usuario" class="form-control" asp-items="ViewBag.UserId" form="#(String.Format("{0}{1}","form",item.StoreID))"></select>
<span asp-validation-for="#item.Usuario" class="text-danger"></span>
</div>
</div>
</td>
It seems it would be cleaner if you define a class UserDTO (or any other name that likes you more)
public class UserDTO
{
public string Name { get; set; }
public string UserName { get; set; }
}
and then you do
var UserNameList = user
.Select(s => new UserDTO { Name = s.Name, UserName = s.UserName })
.ToList();
UserNameList.Insert(0, new UserDTO { Name = "Liquidador", UserName = "--Select--"} );
OTOH... smells a little to add the empty element as part of the data array, my recommendation is to handle that on razor view and just send UserNameList with real data. Dropdown razor methods contains overloads to specify the empty element text.
If you show your HTML, we may help you to implement a better solution.

Maintain DropdownList Selected value in mvc

I have a DropDown and on selcted indexchanged it forcefully postback and Binds a table,but after postback it didn't maintain the state.
my view is
#Html.DropDownListFor(m=>m.fkSubMenuID, (IEnumerable<SelectListItem>)ViewBag.list,"Select"
,new { id = "ddlSubMenu",onchange="SelectedIndexChanged()" })
and my controller is
public ActionResult ChildMenuOfSubMenu()
{
if (Session["DDlId"] == null || Convert.ToInt32(Session["DDlId"]) == 0)
{
UlrikenEntities dc = new UlrikenEntities();
var query = (from m in dc.ulriken_tblChildMenu
join sb in dc.ulriken_tblSubMenu on m.fkSubMenuID equals sb.pkSubMenuID
where m.Status == true && sb.fkMainMenuID == 1
select m).ToList();
Ulriken.Models.ChildMenu ObjHomeEvents = new Models.ChildMenu();
ObjHomeEvents.FormDetails = query;
FillDeptName();
Session["DDlId"] = null;
return View(ObjHomeEvents);
}
else
{
Int64 id = Convert.ToInt64(Session["DDlId"]);
UlrikenEntities dc = new UlrikenEntities();
var query = (from m in dc.ulriken_tblChildMenu
join sb in dc.ulriken_tblSubMenu on m.fkSubMenuID equals sb.pkSubMenuID
where m.Status == true && m.fkSubMenuID == id && sb.fkMainMenuID==1
select m).ToList();
Ulriken.Models.ChildMenu ObjHomeEvents = new Models.ChildMenu();
ObjHomeEvents.FormDetails = query;
FillDeptName();
//string ddlValue= ViewData.TemplateInfo.GetFullHtmlFieldId("ddlSubMenu");
Session["DDlId"] = null;
return View(ObjHomeEvents);
}
//return View();
}
and my javascript function is :
function SelectedIndexChanged() {
document.demoForm.submit();
}
Somebody guide me where am i doing wrong
Your controller action has no parameters... You need at least one parameter in the controller action to retrieve the value selected by the user.
public ActionResult ChildMenuOfSubMenu(int fkSubMenuID)
{
// ....
}
Probably will be better to have a method to show the view when the request is an HTTP GET and another one to handle the form submit (HTTP POST):
public ActionResult ChildMenuOfSubMenu()
{
// This method gets called in a HTTP GET
}
[HttpPost]
public ActionResult ChildMenuOfSubMenu(int fkSubMenuID)
{
// This one gets called when user performs the submit to the form
}

how to store view model value to session

i already try to store my viewmodel to session.
i store my database to viewmodel, and i want to save viewmodel value to session
i try to use
List<GetUserNameViewModel> getName = _accountService.GetLoginName(UserID)
Session["GetName"] = getName;
but value is
System.Collections.Generic.List`1[XNet.Repository.Model.GetUserNameViewModel], not Username...
how can i save my viewmodel value to session??
this my service
public List<GetUserNameViewModel> GetLoginName(int UserID)
{
List<User> user = (from d in _UserRepository.All()
where d.UserID == UserID
select d).ToList();
List<GetUserNameViewModel> GetName = new List<GetUserNameViewModel>();
foreach (User users in user)
{
GetName.Add(new GetUserNameViewModel
{
UserName = users.UserName
});
}
return GetName;
}
my controller
public ActionResult Index()
{
int UserID = Convert.ToInt32(User.Identity.Name);
List<GetUserNameViewModel> getName = _accountService.GetLoginName(UserID);
Session["GetName"] = getName;
return View();
}
In the View (Razor), you've to cast the object in order to traverse the List<T> if that list has two or more GetUserNameViewModel object references or just call FirstOrDefault() method to read the first or default element from the List<T>,
#{
List<GetUserNameViewModel> getNames = Session["GetName"] as List<GetUserNameViewModel>;
for(var name in getNames){
//statements
}
//Or
GetUserNameViewModel name = getNames.FirstOrDefault();
}
And in other case, change the GetLoginName method. I think GetLoginName method should returns an object not a List<T>.
public GetUserNameViewModel GetLoginName(int UserID)
{
User user = (from d in _UserRepository.All()
where d.UserID == UserID
select d).FirstOrDefault();
if(user==null)
return null;
return new GetUserNameViewModel() { UserName = user.UserName };
}

Pass a value from controller to view

I have a problem in passing a value from controller to view
In controller, In the edit method
public ActionResult Edit( FormCollection form)
{
var id = Int32.Parse(form["CustomerServiceMappingID"]);
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
TryUpdateModel(serviceToUpdate, new string[] { "CustomerID", "ServiceID", "Status" }, form.ToValueProvider());
if (ModelState.IsValid)
{
try
{
var qw = (from m in datacontext.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
ViewData["CustomerID"] = qw;
datacontext.SubmitChanges();
//return Redirect("/Customerservice/Index/qw");
return RedirectToAction("Index", new { id = qw });
}
catch{
}
}
return View(serviceToUpdate);
}
Now in edit's view , I used this
#Html.Encode(ViewData["CustomerID"])
This is my Index method
public ActionResult Index(int id)
{
var dc = new ServicesDataContext();
var query = (from m in dc.Mapings
where m.CustomerID == id
select m);
// var a = dc.Customers.First(m => m.CustomerId == id);
// ViewData.Model = a;
// return View();
return View(query);
}
But the customerID on the page turns to be null.. Can u let me know if this procedure is correct?
You don't need to requery the id. Just use the id directly:
if (ModelState.IsValid)
{
datacontext.SubmitChanges();
//return Redirect("/Customerservice/Index/qw");
return RedirectToAction("Index", new { id = id});
}
Since you are redirecting the ViewData["CustomerID"] will be lost.
However the id in your Index method should be valid.
If your Index View requires the ViewData["CustomerID"] set it in your Index action:
public ActionResult Index(int id)
{
ViewData["CustomerID"] = id;
//....
I'm a bit confused as to which view does not have access to ViewData["CustomerId"]. If it's the Index view, you should set ViewData["CustomerId"] = id there.

Resources