我是 MVC 的新手,想在这里获得一些关于如何将变量值从一个 Controller 传递到另一个 Controller 的建议。基本上,我想要实现的是执行 Facebook 身份验证,身份验证成功后,我应该获得 AccessToken 值和我想将其传递给另一个 Controller 以进一步处理的完整路径变量值新观点。我不确定到目前为止我所做的是否有意义:
我有一个像这样的 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;
}
在我的索引 View 中:
<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' });
};
在上面的 View 中,我重定向到另一个页面调用“Publish”,它的 Controller Index ActionResult 需要 fbAcess 和 fullpath 变量进一步处理的值(value)。请建议我如何传递这些值。
请您参考如下方法:
使用重定向:
[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;
}
});
