I try to pass data from login view to Empinput view. I try to use Http session was not working for data passing.
I got this error:
"HttpSessionStateBase' does not contain a definition for 'SetString' and no accessible extension method 'SetString' accepting a first argument of type 'HttpSessionStateBase' could be found".
I put code below please tell me how to pass data?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DemoEmployee.Models;
using System.Web.Security;
using System.Web.UI.WebControls;
using Microsoft.AspNetCore.Http;
public ActionResult Login(Models.Member model)
{
var userr = db.User.Where(x => x.UserName == model.UserName && x.Password == model.Password).FirstOrDefault();
name = model.UserName;
if (userr == null)
{
ModelState.AddModelError("", "Invalid username and password");
FormsAuthentication.SetAuthCookie(model.UserName, false);
}
else
{
// This is not working for passing data to another view
HttpContext.Session.SetString("Username", model.UserName.ToString());
return RedirectToAction("Empinput", "Empinput");
}
return View();
}
[HttpPost]
public ActionResult Empinput(Employee model)
{
Member member = new Member();
Login sdm = new Login();
// this is not working for passing data from Login view
String name = HttpContext.Session.GetString("Username");
}
It's really easy. You can pass your data to view by ViewBag
.
In your controller:
ViewBag.[write a name for View Bag] = [Your Value]
It's like a variable but it's dynamic.
In your for example View:
<td>@ViewBag.[Viewbag name]</td>
There are different approaches to pass values from a controller to a view.
In your controller function, you may initialize a TempData and then use it in your view. But it will only hold the value in one request. For eg, TempData["UserName"] = model.UserName;
and then in the view, You can either store the value to a variable and then display the variable value or display the tempData value directly. eg,
var UserName = TempData["UserName"] as string;
ViewData also behaves and operates like a TempData
ViewData["UserName"] = model.UserName;
and then use it in the view.
In controller,
ViewBag.UserName = model.UserName
and in View you can use it as
@ViewBag.UserName
Session["UserName"] = model.UserName;
I hope this helps you! All the best.
Just call it as a method brother.
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
}
public class EmployeeController : Controller
{
public EmployeeController()
{
}
public async Task<IActionResult> Login()
{
var emp = new Employee()
{
ID = 1,
Name = "Vladimir Bacosa"
};
await EmpInput(emp);
return View();
}
[HttpPost]
public async Task<IActionResult> EmpInput(Employee emp)
{
Console.WriteLine(emp.Name);
return View();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.