【发布时间】: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 TagName、int TagId、List 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