在同一视图中为不同模型添加表单

时间:2014-05-21 20:38:37

标签: entity-framework asp.net-mvc-4 razor

让我们说我有两个模特课;项目,评论如下:

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; }
}

当我创建&#34;控制器和视图时,我使用了CRUD创建功能。对于我的Project类。

现在,在&#39;细节&#39;对于项目的视图,我想添加表单来为这个项目添加评论,我想要&#39;详细信息&#39;看起来像是:

Project Name : -- Project Name Goes Here --

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

提交按钮应该在项目的评论列表中添加评论。

我如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

我建议创建一个ViewModel,它代表视图所需的所有数据。这些ViewModel特定于MVC。

型号:

public class IndexViewModel
{
  public Project Project { get; set; }
  public IEnumerable<Comment> Comments { get; set; }
  public Comment NewComment { get; set; }
}

控制器方法:

public ActionResult Index()
{
  var model = new IndexViewModel();

  // populate data, including an empty NewComment
  model.NewComment = new Comment();
  model.NewComment.ProjectId = model.Project.ProjectId;

  return View(model);
}

查看:

@model IndexViewModel

@using (Html.BeginForm("Comment", "Create"))
{
  @Html.EditorFor(m => m.NewComment.CommentText)

  @Html.HiddenFor(m => m.NewComment.ProjectId)
}

这意味着添加或删除视图所需的数据非常简单。表单应该只需要在NewComment周围。帖子模型看起来像:

型号:

public class CreateCommentViewModel
{
  public Comment NewComment { get; set; }
}

控制方法:

public ActionResult Create(CreateCommentViewModel model)
{
  // logic for creating comment
}

DotNetFiddle Example。 Dot Net Fiddle的唯一问题是它只支持单个视图(我知道),所以当你传递新评论的Text时,我会在评论文本中抛出异常。

答案 1 :(得分:0)

Erik Philips接近回答,实际上他的解决方案有效,但我使用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 })
}

感谢您在这篇文章中做出贡献