how to store view model value to session - asp.net

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 };
}

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.

Session value isn't recognized through controller in MVC Core 2.0. "Nullable object must have a value."

So I'm trying to get a little login system started. When logged in I'd like to transfer the ID from the login method to the index method.
Here's my login method
public async Task<IActionResult> Login(Models.DB.Teacher m)
{
var teacher = await _context.Teacher
.FirstOrDefaultAsync(p => p.Username == m.Username);
if (teacher == null)
{
return View(m);
}
if (m.Password.ToLower() == teacher.Password.ToLower()) //Checks if pass is the same
{
HttpContext.Session.SetInt32("sessionID", teacher.Id);
int _id = (int)HttpContext.Session.GetInt32("sessionID");
return RedirectToAction("/Index/");
}
return View(m);
}
Notice that the int _id = Session on above was just for a test. It worked in the same method.
public async Task<IActionResult> Index()
{
int _id = (int)HttpContext.Session.GetInt32("sessionID");
var teacher = await _context.Teacher
.FirstOrDefaultAsync(p => p.Id == _id);
return View(teacher);
}
This is my error message. I realise it doesn't have any value but I'm clueless as to why.
InvalidOperationException: Nullable object must have a value.
System.Nullable<T>.get_Value()
fifty.Controllers.TeachersController.Index() in TeachersController.cs
+
int _id = (int)HttpContext.Session.GetInt32("ID");

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
}

ASP.NET MVC create a new database record

I've been learning asp.net mvc 3. So, basically I'm trying to create a new record in database. However, I'm trying to keep a particular record predefined
public ActionResult Create()
{
var dc = new ServicesDataContext();
var model = new Maping();
var query = (from m in dc.Customers
where m.CustomerId == model.CustomerID
select m.CustomerId);
ViewData["CustomerID"] = query.First();
return View(model);
}
//
// POST: /Customerservice/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="CustomerServiceMappingID")] Maping serviceToCreate, FormCollection form)
{
if (!ModelState.IsValid)
return View();
var dc = new ServicesDataContext();
dc.Mapings.InsertOnSubmit(serviceToCreate);
try
{
dc.SubmitChanges();
}
catch (Exception e)
{
}
try
{
var id = Int32.Parse(form["CustomerID"]);
ViewData["CustomerID"] = id;
return RedirectToAction("Index", new { id = id });
}
catch
{
return RedirectToAction("INDEX", "Home");
}
}
So this is what I did. So, the case is that id value in second action method is what i needed. However the second method gets redirectd to index so viewdata value is lost.And the thing i did in the first crate method is wrong because no value is assigned. So, can u please help me with this problem.
Use TempData, not ViewData - it will be valid until it is read again. Also why are you adding it into viewdata when it is being passed as a parameter in the RedirectToAction?

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