在同一视图中为不同模型添加表单 [英] Adding Form For Different Model In Same View

查看:80
本文介绍了在同一视图中为不同模型添加表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有两个模型课;项目,并进行以下注释:

Lets's Say that i have a two model classes; Project, and Comment as following :

public class Project
{
    Public int ProjectID { get; set; }
    public string Title { get; set; }
    public virtual List<Comment> Comments { get; set; }
}

public class Comment
{
    Public int CommentID { get; set; }
    public string Text { get; set; }
}

在创建控制器和视图时,我使用了CRUD创建功能

I used the CRUD creation feature when i created the "controller and the views" for my Project class.

现在,在该项目的详细信息视图中,我想添加表格以向该项目添加注释,我想要详细信息的视图应该是这样的:

Now, in the 'Details' view for the Project, i want to add form to add comments to this project, i want the 'Details' view to be something like :

Project Name : -- Project Name Goes Here --

Comments : 1. ---------
           2. ---------
[Text Area To Enter Comment] and [SUBMIT] button

提交按钮应将注释添加到项目的注释列表中。

The submit button should add comment to the project's comments list.

我该如何实现呢?

推荐答案

埃里克·飞利浦(Erik Philips)接近回答,实际上他的解决方案可行,但是我找到了最准确的答案我的问题是使用Html.Action。

Erik Philips was close to answer, actually his solution works, but i found most accurate answer to my question using Html.Action.

// 1. Add this line to Project's Detail View.
@Html.Action("CreateComment","Comment", new { ProjectID = Model.ProjectID })

// 2. Add this method to the Comment Controller class, and send the id 
//    to the comment view.
public ActionResult CreateComment(int ProjectID)
{
    return View(new Comment() { ProjectID = ProjectID });
}

// 3. Create view for the CreateComment controller action
@using (Html.beginForm("SubmitComment","Comment"))
{
    @Html.HiddenFor(ProjectID=>Model.ProjectID) // This value you send it
    @Html.EditorFor(model=>Model.Text)
    <input type="submit" value="Add Comment" />
}

// 4. add method to the comment controller
//    since i alreay public ActionResult Details(int id) in the project controller 
//    to display the project's details and comments. i will call it after adding comment
public ActionResult SubmitComment(Comment comment)
{
    dbContext = new myDatabaseContext();
    dbContext.Comments.Add(comment);
    dbContext.SaveChanges();
    return RedirectToAction("Details","Project", new { id=comment.ProjectID })
}

感谢您为此帖子做出贡献

Thanks for contributing in this post

这篇关于在同一视图中为不同模型添加表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆