2014-08-27 5 views
0

StudentModel.체크 박스 목록 - 게시 : 생성 - NullReferenceException

namespace mvcApp.Models 
{ 
    public class StudentModel 
    { 
     [Display(Name = "First Name")] 
     public string FirstName { get; set; } 
     [Display(Name = "Last Name")] 
     public string LastName { get; set; } 
     [Display(Name = "Email Address")] 
     public string EmailAddress { get; set; } 

     public List<SchoolOrganization> Organizations { get; set; } 
    } 

    public class SchoolOrganization 
    { 
     public string Name { get; set; } 
     public bool IsInvolved { get; set; } 
    } 
} 

학생은 여러 조직에 참여합니다.

컨트롤러

namespace mvcApp.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 

      return View(); 
     } 


     public ActionResult StudentInformation() 
     { 
      // populate student with data 
      var student = new StudentModel() { FirstName = "Joe", LastName = "Doe", EmailAddress = "[email protected]"}; 

      // Populate with Organizations 
      student.Organizations = new List<SchoolOrganization>(); 

      student.Organizations.Add(new SchoolOrganization() { Name = "Math Club", IsInvolved = true}); 
      student.Organizations.Add(new SchoolOrganization() { Name = "Chess Club", IsInvolved = false }); 
      student.Organizations.Add(new SchoolOrganization() { Name = "Football", IsInvolved = true }); 

      return View(student); 
     } 

     **[HttpPost] 
     public ActionResult StudentInformation(StudentModel student) 
     { 
      Response.Write("Name: " + student.FirstName); 

      foreach (var o in student.Organizations) 
      { 
       Response.Write(o.Name + " : " + o.IsInvolved.ToString()); 
      } 
      return View(); 
     }** 
    } 
} 
데이터는 결국 데이터베이스에서 채워집니다

.

보기

@model mvcApp.Models.StudentModel 

@{ 
    ViewBag.Title = "StudentInformation"; 
} 

<h2>StudentInformation</h2> 

@using (Html.BeginForm()) { 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>StudentModel</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.FirstName) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.FirstName) 
      @Html.ValidationMessageFor(model => model.FirstName) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.LastName) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.LastName) 
      @Html.ValidationMessageFor(model => model.LastName) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.EmailAddress) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.EmailAddress) 
      @Html.ValidationMessageFor(model => model.EmailAddress) 
     </div> 

     <div> 
      <table> 
        <tr> 

         <td>Organization Name</td><td>Is Involved</td> 
        </tr> 
       @for (int i = 0; i < Model.Organizations.Count; i++) <== System.NullReferenceException here 
       { 
        @Html.HiddenFor(m => m.Organizations[i].IsInvolved) 
        <tr> 
         <td>@Html.DisplayFor(m => m.Organizations[i].Name)</td> 
         <td>@Html.CheckBoxFor(m => m.Organizations[i].IsInvolved)</td> 
        </tr> 
       } 
      </table> 

     </div> 
     <p> 
      <input type="submit" value="Save" /> 
     </p> 
    </fieldset> 
} 

위의 코드는 HttGet 괜찮 표시합니다. 그러나, 내가 System.NullReferenceException 얻을 업데이트하려고 할 때. https://www.dropbox.com/s/dz0bg3hkd0yq8e3/studentInformation.png?dl=0

아무도 도와 줄 수 있습니까?

감사합니다.

답변

0

제공하신 코드 샘플에서; HomeController의 [HttpPost] ActionResult for StudentInformation은 업데이트 된 개체 모델의 새 인스턴스를 만들어 뷰에 전달하지 않지만 대신 기본 debug.writeline 루틴을 실행합니다. 결과적으로 "StudentInformation.cshtml"의 [HttpPost] 뷰에 대한 종속 뷰는 업데이트 된 모델의 채워진 인스턴스를 수신하지 않습니다 ...

"StudentInformation"모델의 첫 번째 줄에 중단 점 설정 .cshtml "페이지를 열고 응용 프로그램을 실행하면 페이지 상단에 참조 된 모델에 데이터가 없음을 보여줍니다.

페이지의 [HttpPost] 버전이 단순히 빈 모델을 렌더링하는 이유는 다음과 같습니다. 생성 된 변경된 데이터 값없이 뷰가 페이지의 첫 번째 줄에서 호출되는 모델 내에 있어야하는 새 데이터 값의 수에 종속적 인 섹션에 도착할 때까지 계속할 수 있습니다.

빈 데이터 모델 세트는 계산할 값이 없으므로 null 참조가됩니다.

업데이트 된 설정 그룹을 보려면 뷰 모델의 [HttpPost] 버전에 "return View (nameOfViewDataSet)"와 같은 새 정보를 반환하는 모델의 인스턴스를 전달해야합니다. 다시 설정하고 수정 된 양식 데이터가있는 모델의 새 버전으로 전달).

실제 뷰에 대한 StudentInformation ActionResult의 [HttpPost] 버전에 상대적인 return View 문을 통해 데이터가 전달 될 때까지 표시 데이터가없고 카운트 함수는 계속해서 null 값을 반환합니다.

도움이되기를 바랍니다.