如何发送ID到其他控制器进行创建?

时间:2018-12-28 20:13:02

标签: c# asp.net routing entity

我试图创建一个表,该表使用当前表的外键显示其他表的项目列表,并能够创建具有当前表id的新行。

我已经尝试创建RouteMap:

    routes.MapRoute(
    name: "GroupsStudents",
    url: "{controller1}/{id}/{controller2}/{action}",
    defaults: new { controller1 = "Groups", id = 
    UrlParameter.Optional, controller2 = "Students", action = 
    "Create" });

和学生中:

 public ActionResult Create(int id)
 {
    ViewBag.GruopID = new SelectList(db.Groups, "GroupID", "Name", 
    db.Groups.First(p => p.GroupID == id));
    return View();
 }

但我收到此错误:匹配的路由不包含“控制器”路由值,这是必需的。

有我的桌子

public class Group
{
    public int GroupID { get; set; }
    [Required]
    public string Name { get; set; }
    [ForeignKey("GroupID")]
    ICollection<Student> Students { get; set; }
}

public class Student
{
    public int StudentD { get; set; }
    public int GroupID { get; set; }
    public Group Group { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Surname { get; set; }
}  

1 个答案:

答案 0 :(得分:0)

也许您可以像这样定义路线:

routes.MapRoute(
    name: "GroupsStudents",
    url: "Groups/{groupId}/{controller}/{action}",
    defaults: new {controller = "Students", action = "Create" });

public ActionResult Create(int groupId)
 {
    ViewBag.GruopID = new SelectList(db.Groups, "GroupID", "Name", 
    db.Groups.First(p => p.GroupID == groupId));
    return View();
 }

此外,我相信groupId参数不应为可选。