【问题标题】:Why is my View not displaying value of ViewBag?为什么我的视图不显示 ViewBag 的值?
【发布时间】:2015-06-23 23:12:46
【问题描述】:

我有一个带有帖子和标签的小博客应用程序。这是我的 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,我的视图是:

@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 的 Create 动作:

// 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。您的模型是强类型的,而 Viewbag 是动态的。不惜一切代价避免它们。

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


【解决方案1】:

ViewBag 在返回视图时使用,而不是在重定向到另一个操作时使用。基本上它不会在单独的请求中持续存在。尝试改用TempData

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

在视图中:

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

【讨论】:

  • 谢谢!但是当我使用TempData.Tag 时出现错误。然后我使用TempData["Tag"]
  • @Geronimo:它可能是字典而不是动态的,这都是徒手代码:) 我会更新答案,谢谢!
猜你喜欢
  • 2013-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
相关资源
最近更新 更多