[英]How to pass Viewdata value to masterpage in Razor MVC4
我在Directory页面中使用Directoryservices登录。 我需要将用户名传递给我的母版页以显示所有页面中的用户名。
我获得了用户名并将其存储在ViewData中。 如何在masterpage中传递viewdata值。
我的代码:
[HttpPost]
public ActionResult Index(LoginModels model)
{
if (ModelState.IsValid)
{
string DisplayUserName = string.Empty;
string LoginUser = model.Userid;
string LoginPassword = model.Password;
string name = model.UserName
if (ValidateActiveDirectoryLogin(LoginUser, LoginPassword, out DisplayUserName) == true)
{
model.UserName = DisplayUserName;
ViewData["UserName"] = "Welcome" + DisplayUserName;
return RedirectToAction("Index", "MPP", new { UserID = LoginUser });
}
else
{
ModelState.AddModelError("","Invalid Username or Password");
}
}
return View();
}
在布局页面中:
@{ @ViewData["UserName"] }
我尝试了以下方式来显示用户名。 但是它会引发一些感染。
编辑:
@foreach (var m in IEnumerable<SampleECommerce.Models.LoginModels>)ViewData["UserName"])
{
@m.UserName
}
存在一些误解,例如,如果将ViewData["UserName"]
设置为字符串值,则会获得IEnumerable<SampleECommerce.Models.LoginModels>
。 这是另一个解决方案:
把它放到布局页面:
<span>@{Html.RenderAction("actionname", "controllername");}</span>
在相关行动中:
public ActionResult actionname() {
string result = getusername();
return Content(result);
}
[NoneAction]
private string getusername(){
return (Membership.GetUser()!= null) ? Membership.GetUser().UserName : "Guest";
}
尝试没有额外的@,即
@{ ViewData["UserName"] }
您需要将语法更改为:
@(ViewData["UserName"])
这可能是最好的( 坏的一堆 )。 实际上,您应该通过控制器的User
属性将User
推送到页面的User
属性(通常在授权属性中,也许您可以读取cookie) - 这样您就不会依赖于类型不安全ViewData
和魔术字符串,用于您将在每个页面上使用的内容。
但无论如何......如果视图因为最后一次return View();
而呈现return View();
如果你改变你的语法,那么你想要做的就行了。
如果没有,那就是当你确实return RedirectToAction("Index", "MPP", new { UserID = LoginUser });
然后你需要将UserName推入TempData
,然后在MPP
控制器上的Index
操作开始时将其读回:
所以:
TempData["UserName"] = "Welcome " + DisplayUserName;
return RedirectToAction("Index", "MPP", new { UserID = LoginUser });
然后在Index
方法的开头,您需要将值从TempData
:
public class MPPController {
public ActionResult Index(){
ViewData["UserName"] = TempData["UserName"];
}
}
你为什么要这样做? 因为RedirectToAction
不呈现页面 - 它告诉客户端对新的Url发出不同的请求 - 因此任何ViewData
或模型或其他任何东西都会被丢弃到服务器。 TempData
仅用于在两个连续请求之间提供临时存储 - 因此它适用于RedirectToAction
方案。
就像我说的那样 - 这实际上是一种很难将用户信息从控制器持续查看的方式,你应该认真地重新考虑它作为紧急事项。
在布局页面中:
<span>@{Html.RenderAction("actionname", "controllername");}</span>
在控制器中存储一个会话变量
[HttpPost]
public ActionResult Index(LoginModels model)
{
Session["username"] = model.UserName;
//remaining code
}
添加一个功能
public ActionResult actionname() {
return Content(Session["username"]);
}
所以这里我们不需要额外的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.