如何将模型从一个视图传递到另一个?

时间:2020-07-16 12:54:43

标签: c# asp.net-mvc

我是MVC的新手,我正在尝试重写其中的JS项目,我的项目中有两个页面,分别是索引和菜单,通过索引,用户只需按一下按钮即可将其重定向到菜单或选择其他语言,然后使用该语言重定向到菜单。

在索引中,我正在从数据库中加载所有用户信息,例如徽标,背景图片以及用户在模型中可以返回或不能返回的操作。 将用户重定向到菜单后,我应该重用该用户模型数据,但是通过环顾四周,我发现我应该使用TempData或ViewBag之类的东西,但它们都不适合我。

所以在索引中,我有这样的按钮:

<a href="#" onclick="location.href='@Url.Action("Menu", "VMenu", new { lang = "IT" })'" id="menu" class="btn btn-sm animated-button thar-three">Menu</a>

通过传递语言将用户重定向到菜单。

我的控制器看起来像这样:

public class VMenuController : Controller
{
    [Authorize]
    public IActionResult Index()
    {
        return View(AuthHelper.GetProfilo(User.Identity as ClaimsIdentity)); // returning Profilo model
    }

    [Authorize]
    public IActionResult Menu(string lang)
    {
        return View(MenuHelper.GetMenu(User.Identity as ClaimsIdentity, lang)); // returning Menu Model
    }

}

但是我不知道哪种方法应该是将Profilo模型传递给菜单的最佳方法...

我尝试通过在Index控制器甚至ViewBag中设置TempData来尝试,但是它们在Menu中都返回了null。

2 个答案:

答案 0 :(得分:2)

如果我的理解正确,您将获得每个会话的用户个人资料信息。您为什么不将这些信息存储在Session对象中?只要您的会话处于活动状态,您就可以从项目中的每个控制器和方法中获取该配置文件信息。

public class VMenuController : Controller
{
    [Authorize]
    public IActionResult Index()
    {
        var userProfile = AuthHelper.GetProfilo(User.Identity as ClaimsIdentity); // fetch from db
        Session["UserProfile"] = userProfile; // set to session.

        return View(userProfile);
    }

    [Authorize]
    public IActionResult Menu(string lang)
    {
        var userProfile = Session["UserProfile"]; // get from session and use it wherever you like.

        return View(MenuHelper.GetMenu(User.Identity as ClaimsIdentity, lang)); // returning Menu Model
    }

}

答案 1 :(得分:0)

代替使用锚,可以使用html帮助器@ Html.ActionLink或@ Ajax.ActionLink来满足您的要求。您可以在Google上搜索此辅助方法的语法。在这种情况下,TempData和ViewBag也应该起作用。

相关问题