C# “如何处理异常”;当对象在视图中打断时,对象引用未设置为对象的实例

C# “如何处理异常”;当对象在视图中打断时,对象引用未设置为对象的实例,c#,asp.net-mvc,C#,Asp.net Mvc,当我运行ASP.NET MVC应用程序时,我遇到了一个异常“对象引用未设置为对象的实例”。它中断的行是: <div> @Html.ActionLink("Back","Index", new { id = @Model.professorId }) </div> 索引方法的视图如下所示: public class StudentEnrollController : Controller { private UniversityInitial stud

当我运行ASP.NET MVC应用程序时,我遇到了一个异常“对象引用未设置为对象的实例”。它中断的行是:

<div>
  @Html.ActionLink("Back","Index", new { id = @Model.professorId })
</div>
索引方法的视图如下所示:

 public class StudentEnrollController : Controller

 {

    private UniversityInitial studentDataSet = new UniversityInitial();


    public ActionResult Index([Bind(Prefix="id")] int professorId)
    {

        var prof = studentDataSet.Professors.Find(professorId);
        return View(prof); // returns a single instance of the professor.So view of the index must not be Ienumerable
    }



    public ActionResult Create()
    {
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,FirstName,LastName,City,professorId")]Student student)

    {
        if (ModelState.IsValid)
        {

            studentDataSet.Students.Add(student);
           studentDataSet.SaveChanges();
            return RedirectToAction("Index",new { id = student.professorId });
        }

        {

            return View(student);
        }
    }
@model UniversityApp.Models.Professor

  <h2>Student enrolled in the subject: @Model.Subject of @Model.FirstName     @Model.Lastname</h2>

    <p>
     @Html.ActionLink("Enroll New Student", "Create", new { professorId =   @Model.Id })
     </p>

    <!--students is a property of the Professor model of type List-->
   @Html.Partial("_StudentEnroll",@Model.students)
@model university pp.Models.Professor
注册科目的学生:@Model.subject of@Model.FirstName@Model.Lastname

@ActionLink(“注册新学生”,“创建”,新建{professorId=@Model.Id})

@Html.Partial(“_StudentEnroll”,@Model.students)
将创建操作更改为:

public ActionResult Create()
{
    var viewModel = new UniversityApp.Models.Student();
    return View(viewModel);
}

将解决眼前的问题。

正如swatsonpicken所说,您必须在GET Create操作中将ViewModel传递给视图。此操作可能必须接受教授的参数

 [HttpGet]
 public ActionResult Create(int professorId) {
     var vm = new  UniversityApp.Models.Student {
         professorId = professorId 
     }
     // best practice: always provide the name of the View you want to render
     return View("Create", vm); 
 }

您没有将视图模型对象传递给Create视图,因此模型为null。Create方法将视图视为学生模型。请看我上面的问题,观点采取的模式是学生是的,我不好。我已编辑了答案以更正此问题。此外,我必须为方法创建提供一个参数。格奥尔格·帕特谢德的回答完全正确。我需要这个参数professorId,因为在我看来,没有该参数的索引方法将引发另一个异常
 [HttpGet]
 public ActionResult Create(int professorId) {
     var vm = new  UniversityApp.Models.Student {
         professorId = professorId 
     }
     // best practice: always provide the name of the View you want to render
     return View("Create", vm); 
 }