我是asp网络Mvc的新手,我正在尝试在mvc 4中创建一个简单的论坛。我可以创建并列出线程和帖子,但我似乎无法弄清楚如何在现有的帖子中添加新帖子线。换句话说,我希望能够将多个帖子连接到特定的ThreadId
。
那么实现这一目标的最佳方法是什么?我应该将@ActionLink
中的值传递给PostController Create method
ThreadId
值吗?或者我可以在PostController中以某种方式处理这个问题吗?任何代码示例或提示都非常感谢。
我有以下课程:
public class Thread
{
public int ThreadId { get; set; }
public DateTime ? PostDate { get; set; }
public string ThreadText { get; set; }
public string ThreadTitle { get; set; }
public virtual UserProfile UserProfile { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string PostTitle { get; set;}
public string PostText { get; set; }
public DateTime ? PostDate { get; set; }
public virtual UserProfile UserProfile { get; set; }
public virtual Thread Thread { get; set; }
[System.ComponentModel.DataAnnotations.Schema.ForeignKey("Thread")]
public int ThreadId { get; set; }
}
答案 0 :(得分:1)
有几种方法可以达到你想要的效果。在这里,我向您介绍使用强类型视图的方法。
我假设您有一个名为 ViewThreadDetail 的视图,其中包含属于给定 threadId 的帖子列表,您还可以在其中提交新帖子。
ThreadController.cs:
public class ThreadDetailViewModel
{
public Thread Thread { get; set; }
public Post NewPost { get; set; }
}
public ActionResult ViewThreadDetail(int id)
{
// load thread from database
var thread = new Thread(){ ThreadId = id, ThreadTitle = "ASP.Net MVC 4", Posts = new List<Post>()};
// assign ThreadId of New Post
var newPost = new Post() { PostTitle = "", PostText = "", ThreadId = id };
return View(new ThreadDetailViewModel() { Thread = thread, NewPost = newPost });
}
ViewThreadDetail.cshtml
@model MvcApplication1.Models.ThreadDetailViewModel
@{
ViewBag.Title = "ViewThreadDetail";
}
<h2>ViewThreadDetail</h2>
<p>List of Posts:</p>
@foreach (var post in Model.Thread.Posts)
{
<div>@post.PostTitle</div>
}
<p>Add a Post:</p>
@Html.Action("NewPost", "Post", Model.NewPost)
您需要一个名为NewPost的PartialView来提交新帖子:
@model MvcApplication1.Models.Post
@using(Html.BeginForm("Add", "Post"))
{
@Html.LabelFor(a=>a.PostTitle);
@Html.TextBoxFor(a => a.PostTitle);
@Html.LabelFor(a => a.PostText);
@Html.TextBoxFor(a => a.PostText);
//A hidden field to store ThreadId
@Html.HiddenFor(a => a.ThreadId);
<button>Submit</button>
}
PostController.cs
public ActionResult NewPost(Post newPost)
{
return PartialView(newPost);
}
public ActionResult Add(Post newPost)
{
// add new post to database and redirect to thread detail page
return RedirectToAction("ViewThreadDetail", "Thread", new { id = newPost.ThreadId });
}