这可能是一个难解的问题,我正在尝试在我的 MVC _layout 页面中获取一个字符串变量
到目前为止我已经
编辑:
@{
string myVariable = @Html.Action("GetUserName", "UserController");
}
我需要在页面上多次显示myVariable
。因此我需要将其存储在某个地方而不是调用
@Url.Action("GetUserName", "UserController");
多次。
有没有办法在mvc中做到这一点?
编辑2:
我用过
字符串 myVariable = ViewBag.GetUserName()
哪里
在我的BaseController()
中,我有
public BaseController(){
ViewBag.GetUserName = new Func<string>(GetUserName);
}
[AllowAnonymous]
public string GetUserName()
{
return "Mark ZuckerBerg";
}
当我运行我的项目时,我得到,
无法对空引用执行运行时绑定(bind)
最佳答案
我认为您想要的是在您的 Controller 操作中调用该操作,并使用结果。您可以将值作为模型传递给 View ,也可以通过 ViewBag 传递。
public ActionResult MyAction()
{
var userName = new UserController().GetUserName();
return View(userName);
//OR
ViewBag.UserName = userName;
return View();
}
或者,如果您想在 _Layout.cshtml 中使用创建子操作,请在 UserController 中:BaseController
[ChildActionOnly]
public ActionResult UserName()
{
return new ContentResult { Content = "Mark ZuckerBerg" };
}
并调用_Layout.cshtml
@{Html.Action("UserName", "User")}
关于javascript - mvc 在布局页面中使用变量而不是其字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32173878/