我有一个带帖子和标签的小博客应用程序。这是帖子:
的模型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; }
}
}
标记的模型包含字符串TagName , int TagId ,列表帖子。
当我创建新帖子时,我使用 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的创建动作:
// 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>
}
答案 0 :(得分:3)
ViewBag
,而不是在重定向到其他操作时使用。基本上它不会在单独的请求中持续存在。请尝试使用TempData
:
TempData["Tag"] = post.SelectedTag.ToString();
并在视图中:
<p><strong>Tag: @TempData["Tag"]</strong></p>