1

我将首先说我是 MVC4 的新手......所以要温柔

我有一个模型

public class LoginModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }

    public double CurrentBalance { get; set; }
}

这只是标准登录模型的扩展,我刚刚添加了 CurrentBalance 变量。

然后,我向 AccountModel 添加了代码,该代码使用用户名和密码登录另一个系统,成功登录后,我用返回的值更新 CurrentBalacnce 值,然后使用 RedirectToAction 加载登录页面。

[AllowAnonymous]
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        //Log into the server

        if (server_loggedIn)
        {
            server.LogOut();
        }
        if (server.LogIn("****", "****", "****") == 0)
        {
            if (server.GetUserInfoByUserName(model.UserName) == 0)
            {
                if (server.GetUserTransactionInfo(model.UserName) == 0)
                {

                    model.UserName = server.m_sLoggedInUser;
                    model.CurrentBalance = server.m_currentBalance;
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

                    return RedirectToAction("Index","Account", new {model});
                }
            }
          }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

正如您所看到的,我现在正在使用标准代码,而我完全了解它,但是当我加载索引页面时,我在模型中得到一个空值

@model Print_Management.Models.LoginModel

@{
    ViewBag.Title = "Your Account";
}

@section Header {
    @Html.ActionLink("Back", "Index", "Home", null, new { data_icon = "arrow-l", data_rel = "back" })
    <h1>@ViewBag.Title</h1>
}

<p>
    Logged in as <strong>@User.Identity.Name</strong>.
    /n\nCurrent Balance <strong>@Model.CurrentBalance</strong>
</p>

<ul data-role="listview" data-inset="true">
    <li>@Html.ActionLink("Deposit", "ChangePassword")</li>
    <li>@Html.ActionLink("Log off", "LogOff")</li>
</ul>

我确信我在做一些非常基本的错误......但任何帮助将不胜感激,因为今后我将需要在视图之间传递变量..

提前致谢

4

1 回答 1

4

重定向时不能传递复杂对象。您必须明确决定要将此模型的哪些属性与重定向一起作为查询字符串参数发送:

return RedirectToAction(
    "Index",
    "Account", 
    new {
        username = model.UserName,
        password = model.Password, // oops, be careful the password will appear in the query string
        rememberMe = model.RememberMe,
        currentBalance = model.CurrentBalance
    }
);

实际上这样做的正确方法是在重定向时不发送任何参数:

return RedirectToAction("Index", "Account");

然后在目标操作中,您将能够从表单身份验证 cookie 中检索当前经过身份验证的用户:

[Authorize]
public ActionResult Index()
{
    string username = User.Identity.Name;

    // Now that you know who the current user is you could easily 
    // query your data provider to retrieve additional information about him
    ...
}
于 2013-01-04T16:13:30.170 回答