1

我是 MVC 的新手,想在这里获得一些关于如何将变量值从一个控制器传递到另一个控制器的建议。基本上,我想要实现的是执行 Facebook 身份验证,并且在成功身份验证后,我应该获取AccessToken值和我想将其传递给另一个控制器的完整路径变量值,以便使用新视图进行进一步处理。我不确定到目前为止我所做的是否有意义:

我有一个 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完整路径变量值以进行进一步处理。请建议我如何传递这些值。

4

2 回答 2

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;
         }
});
于 2012-08-14T10:38:29.667 回答
1

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

return RedirectToAction("ActionName", "Controller", new {variable1 = value1, variable2 = value2/*...etc*/});
于 2012-08-14T10:38:15.077 回答