如何通过Button链接携带ViewBag元素

时间:2018-02-15 13:48:35

标签: c# asp.net entity-framework viewbag

我正在使用一个使用C#的.NET实体框架应用程序,我正在尝试构建它,所以当有人在应用程序上注册时,他们会被带到Add模板,在那里他们创建一个配置文件。

具体而言,我尝试做的是让表单采用全新的UserID,当他们注册并填写表格中的一个字段时,会生成UserId并将新配置文件与用户匹配。

我试图使用ViewBags的概念来做到这一点,但我遇到了一个问题。

在大多数情况下,应用程序视图使用ActionLinks处理ViewBags,如下所示:

@Html.ActionLink("View University Course", "GetNAA_University_Courses", new { ApplicantId = ViewBag.ApplicantId, UniversityId = item.UniversityId, Controller ="NAAAdmin" })

但是我的Register函数视图并没有使用ActionLinks,它使用了这样的按钮函数:

 <div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" class="btn btn-default" value="Register" />
    </div>
</div>

我正在尝试在帐户控制器中的此寄存器方法中传递UserId viewbag,您可以看到它使用管理控制器将用户重定向到AddNAA_Profile函数。

 // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model, string UserId)
    {
        ViewBag.UserId = UserId;
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                UserManager.AddToRole(user.Id, "User");
                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("AddNAA_Profile", "NAAAdmin");
            }
            AddErrors(result);
        }

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

有谁知道如何理想地将Register视图中的ViewBag变量传递给AddNAA_Profile表单?

1 个答案:

答案 0 :(得分:0)

首先,如果我没有误会,如果您执行RedirectToAction(),ViewBag将被清除,因为它只会在当前的HTTP请求中保留。如果您希望它在RedirectToAction()中保留,则应使用TempData["UserId"]=UserId.

要在表单中访问它,您可以使用@TempData["UserId"]