mvc-将数据从控制器传递到其他控制器的视图

mvc-pass data from controller to view of other controller

我有一个 AccountController,其中我有一个动作 YNHHConsentForm 在此动作中,我正在使用 RedirectToAction("Index", "Default") 重定向到另一个视图。现在我想在默认的索引页面上显示一条消息。我尝试使用 ViewBagViewData 传递值,但它仍然是 null,我无法在 Index.

上使用它的值

账户控制器

   public ActionResult YNHHConsentForm(YNHHFormVM model)
    {
        if (result == 0 || isSuccess == false)
        {
            model.FormSubmissionMessage = "Something went wrong please try again";
            return View(model);
        }
        else
        {
            SessionItems.IsAuthorizationFormFilled = true;
            //ViewBag.FormSubmissionMessage="Form submitted successfully";
            ViewData["FormSubmissionMessage"] = "Form submitted successfully";
            return RedirectToAction("Index", "Default");
        }
    }

索引(默认)

   @if (ViewData["FormSubmissionMessage"] !=null)
            {
                <div class="alert alert-success">
                    ViewData["FormSubmissionMessage"].ToString()
                </div>
            }

我是第一次使用 ViewBagViewData,所以无法找出我哪里做错了。

您需要使用 TempData。在YNHHConsentForm()方法中

TempData["FormSubmissionMessage"] = "Form submitted successfully";
return RedirectToAction("Index", "Default");

并在 Index() 方法中访问它(并将其添加到(比如)ViewBag,这样您就可以在视图中访问它了。

ViewBag.MyMessage = TempData["FormSubmissionMessage"];

并在视图中

<div class="alert alert-success">@ViewBag.MyMessage</div>

有关 ViewData ViewBagTempData 之间差异的解释,请参阅 this answer

旁注:TempData 仅持续一次重定向,因此如果用户刷新浏览器,则不会再次生成消息。如果它很关键,你可以使用 .Keep().Peek() 来解决这个问题(更多细节请参考 this answer

为了补充@StephenMueke 的回答,我通常会为您似乎正在使用的场景创建一对组件(显示系统确认)。它包括:

  1. 包含 status/alert 类型字符串的静态 class。
  2. 在布局上呈现的局部视图,以便消息位于一致的位置。

静态 class 看起来像这样:

public class Alert
{
    public static string Error = "alert-error alert-danger";
    public static string Info = "alert-info";
    public static string Warning = "alert-warning";
    public static string Success = "alert-success";

    public static string[] All = new string[]{ Error, Info, Warning, Success };
}

本质上,这些是 Bootstrap 警报 classes,但它们足够通用,可以在没有 Bootstrap 的情况下工作。 Alert.Error 值包含两个 "classes" 以使其与 Bootstrap.

的版本 2 和版本 3 兼容

部分视图检查 TempData 中的 Alert 值,如果找到则生成 Bootstrap 警报:

@foreach (string key in Alert.All)
{
    if (TempData.ContainsKey(key))
    {
        <div class="alert @key">
            <button type="button" class="close" data-dismiss="alert"><i class="fa fa-fw fa-times"></i></button>
            @Html.Raw(TempData[key])
        </div>
    }
}

我使用 Html.Raw 以便我可以在消息中包含标记,如果我想强调消息的一部分:

TempData.Add(Alert.Success, "<b>Thank you!</b> Form submitted successfully!");

将呈现为:

Thank you! Form submitted successfully!