如何将值从一个控制器传递到ASP.Net MVC3中的另一个控制器 [英] How to pass values from One controller to another Controller in ASP.Net MVC3

查看:111
本文介绍了如何将值从一个控制器传递到ASP.Net MVC3中的另一个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,在我的项目中,我必须将带有 username 的欢迎消息传递到索引页面它是一个MVC3 ASP.Net Razor项目

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

有两个控制器.一个是登录控制器,第二个是本地控制器.从Login Controller,我必须将Login Person的 UserName 传递给视图Page.

There are two controllers are there; One is Login Controller and the second one is Home Controller. From Login Controller, I have to pass UserName of the Login Person to the view Page.

Login Controller重定向到另一个名为Home Controller的控制器.从那里我必须将该值传递到视图页面.那是我的问题.我已经尝试过使用单个控制器来查看其工作情况.

Login Controller redirect to Another controller called Home Controller .From there I have to pass that value to the view page. That's my issue. I have tried with single controller to view, its working.

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

I cant use the single controller because Login Controller uses Login Page and Home Controller uses Home Page. Both are separate views.

我已经尝试过像这样,但是它不起作用.您能建议一个好的方法吗?

I have tried Like this, but its not working. Can you suggest a good Method to follow?

登录控制器

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();
}

推荐答案

您可以尝试使用Session,例如

You can try with Session, like

Session["username"] = username;

并在其他控制器中恢复使用

and for recover in the other controller use

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

或在您的重定向中尝试

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();
}

这篇关于如何将值从一个控制器传递到ASP.Net MVC3中的另一个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆