How to pass values from One controller to another Controller in ASP.Net MVC3

后端 未结 4 693
青春惊慌失措
青春惊慌失措 2021-01-14 08:19

Hello In my project I have to pass a welcome message with username to the Index Page Its a MVC3 ASP.Net Razor project

There are two controllers are there; O

相关标签:
4条回答
  • 2021-01-14 08:58

    Use TempData. Its data is available in the next request also.

    // after login
    TempData["message"] = "whatever";
    
    // home/index
    var message = TempData["message"] as string;
    
    0 讨论(0)
  • 2021-01-14 08:59

    You can try with Session, like

    Session["username"] = username;
    

    and for recover in the other controller use

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

    or in your redirect try with

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

    but the action of your controller must have as argument the (string username) like

    public ActionResult Index(string username)
    {
        return View();
    }
    
    0 讨论(0)
  • 2021-01-14 09:05
    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
      }
      

    Go to the View Page of the Index method of Home Controller and add the following:

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

    And you're done. :)

    0 讨论(0)
  • 2021-01-14 09:22

    You could retrieve the currently authenticated username from the User instance:

    [Authorize]
    public ActionResult Index()
    {
        string username = User.Identity.Name;
        ...
    }
    
    0 讨论(0)
提交回复
热议问题