c# - 为什么我的 View 不显示 ViewBag 的值?

标签 c# asp.net asp.net-mvc asp.net-mvc-4 razor

我有一个带有帖子和标签的小型博客应用程序。这是我的Post 模型:

namespace HelloWorld.Models
{
    public class Post
    {
        [Required]
        [DataType(DataType.Text)]
        public string Title { get; set; }

        [Required]
        [DataType(DataType.MultilineText)]
        public string Description { get; set; }

        [Required]
        [DataType(DataType.DateTime)]
        public DateTime PostDate { get; set; }

        public List<Tag> Tags { get; set; }

        [Required]
        public int PostId { get; set; }
    }

    public class CreatePostView
    {
        [Required]
        [DataType(DataType.Text)]
        public string Title { get; set; }

        [Required]
        [DataType(DataType.MultilineText)]
        public string Description { get; set; }

        [Display(Name = "Tags")]
        [Required(ErrorMessage = "Please select a tag")]
        public string SelectedTag { get; set; }
        public SelectList TagList { get; set; }

        [Required]
        public int PostId { get; set; }
    }
}

Tag模型由string TagNameint TagIdList Posts组成。

当我创建新帖子时,我使用 CreatePostView 并且我的 View 是:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="create-post-form">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">

            <strong>Title</strong>

            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">

            <strong>Description</strong>

            <div class="col-md-10">
                @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
            </div>
        </div>

        @Html.DropDownListFor(m => m.SelectedTag, Model.TagList, "Add tag")
        @Html.ValidationMessageFor(m => m.SelectedTag)

        <div class="post-create-button">
            <input type="submit" value="Create">
        </div>

        <div class="back-to-list-button">
            @Html.ActionLink("Back", "Index")
        </div>
    </div>
}

现在我想显示我选择的标签。我将所选标签的值放入 ViewBag,但它不显示。也许这很愚蠢,但我不知道如何解决。我的 PostsController 创建操作:

// POST: Posts/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreatePostView post)
        {
            Post currPost = new Post {
                                       Title = post.Title, 
                                       Description = post.Description, 
                                       PostDate = DateTime.Now, 
                                       Tags = null };

            ViewBag.Tag = post.SelectedTag.ToString();
            ViewBag.Trash = "texttexttexttexttext"; // It's strange, but it not displayed.

            if (ModelState.IsValid)
            {
                //var tags = db.Tags.Where(s => s.TagName.Equals(post.SelectedTag)).ToList();     
                //currPost.Tags = tags;

                db.Posts.Add(currPost);
                db.SaveChanges();
                return RedirectToAction("Index", "Posts");
            }

            return View(currPost);
        }

我对所有帖子的看法(使用模型帖子)

@foreach (var item in Model)
    {
        <article class="post">
            <h3>@Html.DisplayFor(modelItem => item.Title)</h3>
            <p>@Html.DisplayFor(modelItem => item.Description)</p>

            <!--None of them is not shown-->
            <p><strong>Tag: @ViewBag.Tag</strong></p>
            <p><strong>Trash: @ViewBag.Trash</strong></p>
        </article>
    }

最佳答案

ViewBag 在返回 View 时使用,而不是在重定向到另一个操作时使用。基本上它不会在不同的请求中持续存在。尝试使用 TempData 代替:

TempData["Tag"] = post.SelectedTag.ToString();

在 View 中:

<p><strong>Tag: @TempData["Tag"]</strong></p>

关于c# - 为什么我的 View 不显示 ViewBag 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31006235/

相关文章:

javascript - 如何在 Action 完成之前显示加载图像 ASP.Net MVC 5

c# - .NET Core 复制子文件夹以在构建和发布时输出

c# - asp.net如何对GridView中的数据进行排序

javascript - D3js 教程未显示任何图形且控制台中没有错误

c# - HttpPostedFileBase 与 HttpPostedFileWrapper 的关系

c# - 使用 MVC 5 和 Entity Framework 下拉关联实体

c# - 为什么 Assert.AreEqual(T obj1, Tobj2) 会因相同的对象而失败

c# - 使用 Task.Factory 清理电子邮件异步

c# - 无法从 X.509 存储获取当前用户证书

C# MVC 模型表达式到值