MVC +将值从一个控制器传递到另一个控制器

时间:2012-08-14 10:30:39

标签: c# asp.net-mvc facebook

我是MVC的新手,想要了解如何将变量值从一个控制器传递到另一个控制器。基本上,我想要实现的是执行Facebook身份验证,并且在成功进行身份验证后,我应该获取 AccessToken 值和fullpath变量值,我想将其传递给另一个控制器以进行进一步处理新观点。我不确定到目前为止我所做的事情是否有意义:

我有一个ActionResult方法(简化为更清晰),如下所示:

[HttpPost]
public ActionResult Index(string facebookUID, string facebookAccessTok)
{
    string fbUID = facebookUID;
    string fbAcess = facebookAccessTok;
    var fullpath = "";

    string uploadPath = Server.MapPath("~/upload");
    fullpath = uploadPath + "\\ProfilePic.png";

    return null;
}

在我的索引视图中:

<script type="text/javascript">
    var uid = 0;
    var accesstoken = '';

    function grantPermission() {
        window.FB.login(function (response) {
            if (response.authResponse) {
                uid = response.authResponse.userID;
                accesstoken = response.authResponse.accessToken;
                var postData = { facebookUID: uid, facebookAccessTok: accesstoken };
                $.ajax({
                    type: 'POST',
                    data: postData,
                    success: function () {
                        // process the results from the controller action
                        window.location.href = "Publish";
                    }
                });
            } else {
                alert('User cancelled login');
            }
        }, { scope: 'publish_stream' });
    };

在上面的视图中,我重定向到另一个页面调用“发布”,其控制器索引ActionResult需要 fbAcess fullpath 变量进一步处理的价值。请告知我如何传递值。

2 个答案:

答案 0 :(得分:3)

使用重定向:

[HttpPost]
public ActionResult Index(string facebookUID, string facebookAccessTok)
{
    string fbUID = facebookUID;
    string fbAcess = facebookAccessTok;
    var fullpath = "";

    string uploadPath = Server.MapPath("~/upload");
    fullpath = uploadPath + "\\ProfilePic.png";

    return RedirectToAction("Publish", "TheOtherController", new { fbAccess = fbAccess, fullpath = fullpath });
}

public class TheOtherController : Controller
{
    public ActionResult Publish(string fbAccess, string fullpath)
    {
        // Do whatever you want
        //
    }
}

如果您使用标准表单将数据提交到Index方法,则此方法有效。如果要保持Ajax发送数据,请按以下方式修改代码:

[HttpPost]
public ActionResult Index(string facebookUID, string facebookAccessTok)
{
    string fbUID = facebookUID;
    string fbAcess = facebookAccessTok;
    var fullpath = "";

    string uploadPath = Server.MapPath("~/upload");
    fullpath = uploadPath + "\\ProfilePic.png";

    var redirectUrl = new UrlHelper(Request.RequestContext).Action("Publish", new { fbAcess = fbAcess, fullpath = fullpath });
    return Json(new { Url = redirectUrl });
}

在您的客户端代码中:

$.ajax({ type: 'POST',
         data: postData,
         dataType: 'json',
         success: function (response) {               
             window.location.href = response.Url;
         }
});

答案 1 :(得分:1)

成功验证后,请调用以下方法

return RedirectToAction("ActionName", "Controller", new {variable1 = value1, variable2 = value2/*...etc*/});