Schoof
Schoof

Reputation: 2855

MVC: Adding new model instance from within view that uses different model

I recently started using MVC, and as a test project I am creating a simple "blog". I have got a basic structure in place where the main page displays all the posts and when you click on it it will go into the detail page.

Structure

Now I am trying to add comments (Comment.cs)to my posts from within the Home/Details view, which basically requires me to have 2 models in 1 view. Model 1 is the Post model and Model 2 is the Comment model;

This is the code for my Home/details view:

@model MVCPortfolio.Models.Post

@{
    ViewBag.Title = "Details";
}

<h2>@Model.Title - @Model.Author</h2>

<fieldset>
    <legend>Posted on @Model.Date.ToShortDateString()</legend>
    <div class="content">
         @Model.Content
    </div>
</fieldset>
    <div class="comments">
        <ul>
            @foreach (var c in Model.Comments)
            {
            <li>
                @c.Content - @c.Author
            </li>
            }
        </ul>
    </div>
<div class="newcomment">
@*  @Html.EditorFor(model => model) *@
</div>

<p>
@* 
    @Html.ActionLink("New Comment", "Comment", new { id = Model.PostId }) 
*@
    |
    @Html.ActionLink("Back to List", "Index")
</p>

And this is my home controller, from within which I want to add comments.

    private PortfolioEntities db = new PortfolioEntities();

    //
    // GET: /Home/

    public ActionResult Index()
    {
        var posts = (from p in db.Posts
                     orderby p.Date
                     select p);

        return View(posts);
    }

    public ActionResult Details(int id)
    {
        var post = (from p in db.Posts
                    where p.PostId == id
                    select p).Single();

        return View(post);
    }

    [HttpPost]
    public ActionResult Comment(Comment comment)
    {
        if (ModelState.IsValid)
        {
            db.Comments.Add(comment);
            db.SaveChanges();

            return RedirectToAction("Details");
        }

        return View(comment);
    }
}

But what I don't understand is how to add the comment to the post, I can easily add a new post (see my Create.cshtml view), but I cannot figure out how to add a comment from within the post detail view.

Thank you for your time, Thomas

Upvotes: 1

Views: 3166

Answers (1)

rexcfnghk
rexcfnghk

Reputation: 15432

In view of the clarifications, I think you should create a partial view for that.

In your view, subsitute

@Html.ActionLink("New Comment", "Comment", new { id = Model.PostId }) 

with a call to render a partial view

@Html.Partial("_Comment")

Your partial view should handle the UI for adding a Comment, ending with a call to your Comment action method in your PostController

Upvotes: 2

Related Questions