如何在ASP.NET MVC页面上展示主从数据?

4
我已经阅读了几篇关于这个主题的SO问题,但是说实话,它们中的大部分对我来说都太复杂了。我对ASP.NET mvc非常陌生。
我有一个示例ASP.NET mvc 4应用程序,我通过遵循(并稍微偏离)电影数据库教程创建了它。 它具有内置的帐户部分,Entity Framework(每当我更改任何内容时都会变得麻烦),以及我基于教程模型构建的两个模型:
1)Bug
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace MasterDetailPractice.Models
{
    public class Bug
    {
        public int BugID { get; set; }
        public string BugTitle { get; set; }
        public DateTime BugDate { get; set; }
        public string BugStatus { get; set; }
        [Column(TypeName = "ntext")]
        [MaxLength]
        public string BugDescription { get; set; }
    }

    public class BugDBContext : DbContext
    {
        public DbSet<Bug> Bugs { get; set; }
        public DbSet<Comment> Comments { get; set; }
    }

}

2) 注释

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace MasterDetailPractice.Models
{
    public class Comment
    {
        public int CommentID { get; set; }
        public int BugID { get; set; }
        public int UserID { get; set; }
        public DateTime CommentDate { get; set; }
        [Column(TypeName = "ntext")]
        [MaxLength]
        public string CommentText { get; set; }
    }
}

当我运行这个应用程序时,我可以访问/Project并获得标准的Index视图,其中包含Add链接,我可以添加一个Bug。添加后,我可以看到通常的Edit/Details/Delete链接。当我运行这个应用程序时,我也可以去/Comment并获取标准的Index视图,其中包含Add链接,我可以添加一个Comment。添加后,我可以看到通常的Edit/Details/Delete链接。到目前为止,我还好。CRUD表单可以正常工作,只是它们不能同时工作。
问题:
目前,为了使评论适用于Bug,我必须在/Comment/Create表单中实际输入BugID。然后,这些评论仅在/Comment/路由中可用。
相反,我需要发生以下情况:
-“添加评论”表单应自动知道要保存哪个BugID,而不需要用户输入。 -数据的主细节表示:/Comment/Index视图应出现在/Bug/Edit和/或Bug/Details页面的底部,并仅显示与当前Bug相关的评论。 -“添加评论”链接应仅从/Bug/Edit或/Bug/Details页面显示,因此永远不会添加评论而不涉及Bug。
太神奇了,我花了3天时间阅读每一篇有关此主题的谷歌搜索结果和SO帖子,但仍无法解决这个问题。说到这里,希望学习最简单的实现方法。
我需要发布更多的代码(例如,控制器或视图)以便这个问题可以得到合适的答案吗?
期待慢学习的火车开始行驶...
1个回答

0

好的,你需要做几件事情。

首先,在 CommentController 中创建一个新的操作方法,它看起来像这样。

public ActionResult Index(int bugId)
{
    // Your logic to fetch all comments by BugID through EntityFramework or whatever
    return View(data);
}

现在,在您的Bug/Edit.cshtml或Bug/Details.cshtml页面中添加以下代码行以呈现这些操作内联。

@Html.RenderAction("Index", "Comment", new { @bugId = Model.BugID }

在这种情况下,你应该将BugModel返回到Bug/Edit.cshtml或Bug/Details.cshtml作为你的模型。
这样就可以展示你需要的表单,其中从模型传递的BugID也会显示出来。
对于你最后一个问题,只需将“添加评论”链接放在Comment/Index.cshtml视图中,因为它只会在bug的上下文中出现。你可能需要将其包装在一个提交到CommentController的表单中。
这里有一个有用的链接,介绍了如何在ASP.NET 4中使用表单。

http://www.asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-helpers,-forms-and-validation


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接