返回带表单数据的视图

时间:2011-08-09 10:56:04

标签: asp.net-mvc asp.net-mvc-3

我有以下控制器。如果发生错误但表单数据丢失,我将返回视图。 有人会知道如何用视图返回表单数据吗?

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Register(FormCollection collection)
    {
        string usrname = collection["UserName"];
        string email = collection["Email"];
        string password = collection["Password"];
        string serial = collection["Serial"];
        ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        // In a real app, actually register the user now
        if (ValidateRegistration(usrname, email, password, password))
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus = MembershipService.CreateUser(usrname, password, email, serial);

            if (createStatus == MembershipCreateStatus.Success)
            {
                //TODO userinformation

                datacontext.SaveChanges();
                FormsAuth.SignIn(collection["UserName"], false /* createPersistentCookie */);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));

                //I would like to return the view with the form data

                return View();
            }
        }

2 个答案:

答案 0 :(得分:2)

你绝对应该使用视图模型,强类型视图并删除任何FormCollection和魔术字符串,如下所示:

public class RegisterUserViewModel
{
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string Serial { get; set; }
    public int PasswordLength { get; set; }
}

然后:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(RegisterUserViewModel model)
{
    model.PasswordLength = MembershipService.MinPasswordLength;
    // In a real app, actually register the user now
    if (ValidateRegistration(model.UserName, model.Email, model.Password, model.Password))
    {
        // Attempt to register the user
        MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email, model.Serial);
        if (createStatus == MembershipCreateStatus.Success)
        {
            //TODO userinformation
            datacontext.SaveChanges();
            FormsAuth.SignIn(model.UserName, false /* createPersistentCookie */);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
            return View(model);
        }
    }

    ...
}

Visual Studio的默认ASP.NET MVC 3应用程序向导在AccountController中创建了如何执行此操作的示例。

答案 1 :(得分:0)

首先,我建议使用PRG pattern(不要从POST操作返回视图)

您需要将ModelState存储在临时数据中,但您可以使用操作过滤器属性轻松完成 - 请参阅此blog post中的第13点。