如何在ASP.Net MVC3中从一个控制器传递值到另一个控制器

4

你好,在我的项目中,我需要将一个带有用户名的欢迎信息传递到主页上。这是一个MVC3 ASP.Net Razor项目。

有两个控制器:一个是登录控制器,另一个是主页控制器。从登录控制器,我必须将登录人的用户名传递给视图页面。

登录控制器重定向到另一个名为主页控制器的控制器。从那里,我必须将该值传递到视图页面。这是我的问题。我已经尝试过使用单个控制器来查看,它可以工作。

我不能使用单个控制器,因为登录控制器使用登录页面,而主页控制器使用主页。两者都是不同的视图。

我已经尝试过像这样的方式,但它没有起作用。您能否建议一种好的方法来遵循?

登录控制器

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();
}
4个回答

19
您可以尝试使用Session,例如:
Session["username"] = username;

如果需要在另一个控制器中进行恢复,请使用以下代码:

var username = (string)Session["username"]

或者在你的重定向中尝试使用以下方法:

return RedirectToAction("Index", "Nome", new{ username: username})

但是您的控制器必须将(string username)作为参数进行操作

public ActionResult Index(string username)
{
    return View();
}

将数据作为参数传递给RedirectToAction不起作用。这个原因在这个答案中已经解释了 - https://dev59.com/io7ea4cB1Zd3GeqPAWO9#32174158 - Abhishek Poojary
根据MSDN和我的实际测试,它可以正常工作。https://msdn.microsoft.com/it-it/library/system.web.mvc.controller.redirecttoaction(v=vs.118).aspx - theLaw

4

您可以从 User 实例中检索当前已验证的用户名:

[Authorize]
public ActionResult Index()
{
    string username = User.Identity.Name;
    ...
}

3
  1. Change the Index() method of Home Controller to this:

    [HttpPost]
    
    public ActionResult Index(string username)
    {
         ViewBag.user=username; 
         return View();
    }
    
  2. Modify the Login Controller :

    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控制器的Index方法的视图页面,并添加以下内容:

 <p>User is: @ViewBag.user</p>

你已经完成了。:)

2
使用TempData。其数据在下一次请求中也可用。
// after login
TempData["message"] = "whatever";

// home/index
var message = TempData["message"] as string;

1
值得注意的是,如果用户刷新页面,这个值就会丢失。 - ᴍᴀᴛᴛ ʙᴀᴋᴇʀ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接