1

我对 asp net Mvc 非常陌生,我正在尝试在 mvc 4 中创建一个简单的论坛。我可以创建和列出线程和帖子,但我似乎无法弄清楚如何将新帖子添加到现有线程。换句话说,我希望能够将多个帖子连接到特定的ThreadId.

那么实现这一点的最佳方法是什么,我应该将一个值传递@ActionLink给我PostController Create methodThreadId值吗?或者我可以在我的 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; }        
}
4

1 回答 1

1

有几种方法可以实现您想要的。在这里,我向您介绍一种使用强类型视图的方法。

我假设您有一个名为ViewThreadDetail的视图,其中包含属于给定threadId的帖子列表,您也可以在其中提交新帖子。

线程控制器.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 });
}

查看ThreadDetail.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 });
}
于 2013-01-22T18:36:16.420 回答