复合主键编辑视图MVC

时间:2014-11-15 21:08:20

标签: asp.net-mvc

您好我正在尝试在包含学生ID和课程ID的链接器表中编辑学生成绩。我已经看了一下,并且已经看到我需要在视图中接受两个id参数而不仅仅是一个id,然后更改动作链接以获取两个参数。但是,当我点击索引中的编辑按钮时,我得到一个404说该页面无法找到。我出错的任何想法? 提前谢谢。

这是我的索引视图

@model IEnumerable<S00132671CA2.Models.StudentCourse>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Grade)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Grade)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id= item.StudentId, CourseId = item.CourseId }) |
            @Html.ActionLink("Details", "Details", new { id = item.StudentId, Course = item.CourseId }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>

这是我的编辑操作

 public ActionResult Edit(int? StudentId, int? CourseId)
        {
            StudentCourse courseList = db.StudentCourse.Find(StudentId, CourseId);
            if (courseList == null)
            {
                return HttpNotFound();
            }
            ViewBag.StudentId = new SelectList(db.Students, "StudentId", "StudentName", courseList.StudentId);
            ViewBag.CourseId = new SelectList(db.Courses, "CourseId", "CourseName", courseList.CourseId);
            return View(courseList);
        }

这是我的模型,如果有任何帮助

public class StudentCourse
    {
         [Key, Column(Order = 0)]
        public int StudentId { get; set; }
         public virtual Student Student { get; set; }
          [Key, Column(Order = 1)]
        public int CourseId { get; set; }
          public virtual Course Course { get; set; }
          public double Grade { get; set; }

    }

1 个答案:

答案 0 :(得分:4)

尝试

@Html.ActionLink("Edit", "Edit", new { StudentId = item.StudentId, CourseId = item.CourseId })