![](/img/trans.png)
[英]How to pass values of the javascript-created-textboxes to asp.net mvc3 controller?
[英]How to pass values from One controller to another Controller in ASP.Net MVC3
您好在我的项目中,我必须将带有用户名的欢迎消息传递给索引页面它是一个MVC3 ASP.Net Razor项目
那里有两个控制器; 一个是登录控制器,第二个是家庭控制器。 从Login Controller,我必须将登录人的UserName传递给视图页面。
登录控制器重定向到另一个名为Home Controller的控制器。从那里我必须将该值传递给视图页面。 那是我的问题。 我试过用单个控制器来查看它的工作情况。
我无法使用单一控制器,因为登录控制器使用登录页面和家庭控制器使用主页。 两者都是不同的观点。
我试过像这样,但它不起作用。 你能建议一个好的方法吗?
登录控制器
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(LoginModel model)
{
if (ModelState.IsValid)
{
if (DataAccess.DAL.UserIsValid(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home" );
}
else
{
ModelState.AddModelError("", "Invalid Username or Password");
}
}
return View();
}
家庭控制器
public ActionResult Index()
{
return View();
}
你可以试试Session,比如
Session["username"] = username;
并在其他控制器使用中恢复
var username = (string)Session["username"]
或者在重定向中尝试使用
return RedirectToAction("Index", "Nome", new{ username: username})
但是你的控制器的动作必须具有(字符串用户名)之类的参数
public ActionResult Index(string username)
{
return View();
}
您可以从User
实例中检索当前经过身份验证的用户名:
[Authorize]
public ActionResult Index()
{
string username = User.Identity.Name;
...
}
使用TempData。 其数据也可在下一个请求中获得。
// after login
TempData["message"] = "whatever";
// home/index
var message = TempData["message"] as string;
将Home Controller的Index()方法更改为:
[HttpPost] public ActionResult Index(string username) { ViewBag.user=username; return View(); }
修改登录控制器:
if (DataAccess.DAL.UserIsValid(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, false); return RedirectToAction("Index", "Home",new { username = model.Username } ); //sending the parameter 'username'value to Index of Home Controller }
转到Home Controller的Index方法的View Page并添加以下内容:
<p>User is: @ViewBag.user</p>
而且你已经完成了。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.