2015-07-09 2 views
0

Я получаю следующую ошибку при попытке сохранить отредактированную информацию в моей форме.Ссылка на объект не установлена ​​в экземпляр объекта asp.net mvc

Первый шанс, исключение типа «System.NullReferenceException» произошло в GRCWebApp.dll

Дополнительная информация: Ссылка на объект не указывает на экземпляр объекта.

Ошибка связана с этой строкой в ​​контроллере: currentMembershipType.Type = model.Type;

Столб Метод

 [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult EditClubMembershipType(EditMembershipTypeViewModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      //Go fetch the membership type from the database 
      var currentMembershipType = db.MembershipTypes.FirstOrDefault(p => p.MembershipTypeId == model.MembershipTypeId); 
      // Save new Membership Type 
      currentMembershipType.Type = model.Type; 
      currentMembershipType.Description = model.Description; 
      currentMembershipType.Cost = model.Cost; 
      currentMembershipType.ReducedCost = model.ReducedCost; 
      currentMembershipType.DayId = model.ReducedDay; 
      currentMembershipType.MonthId = model.ReducedMonth; 
      currentMembershipType.MinAge = model.MinAge; 
      currentMembershipType.MaxAge = model.MaxAge; 
      // Save Changes 
      db.SaveChanges(); 
      return RedirectToAction("AddClubMembershipType", new { clubId = model.ClubId, editMode = true }); 
     } 
     return View("Error"); 
    } 

Зрения:

@model GRCWebApp.ViewModels.EditMembershipTypeViewModel 


@using (Html.BeginForm()) 
{ 
@Html.AntiForgeryToken() 
@Html.HiddenFor(model => model.ClubId) 
<div class="col-md-12"> 
    <h3>Edit Membership Type</h3> 
</div> 
<div class="form-horizontal"> 
    <hr /> 
    <div class="row"> 
     <div class="col-md-10"> 
      <div class="well bs-component"> 
       <div class="form-group"> 
       </div> 
       @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
       <div class="form-group"> 
        <div class="row col-offset-md-1 col-md-11"> 
         <div class="col-md-3"> 
          @Html.LabelFor(model => model.Type, htmlAttributes: new { @class = "control-label" }) 
          @Html.EditorFor(model => model.Type, new { htmlAttributes = new { @class = "form-control", placeholder = "e.g. Full" } }) 
          @Html.ValidationMessageFor(model => model.Type, "", new { @class = "text-danger" }) 
         </div> 
         <div class="col-md-4"> 
          @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label" }) 
          @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } }) 
          @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" }) 
         </div> 
         <div class="col-md-2"> 
          @Html.LabelFor(model => model.Cost, htmlAttributes: new { @class = "control-label" }) 
          <div class="input-group"> 
           <div class="input-group-addon"> £</div>@Html.EditorFor(model => model.Cost, new { htmlAttributes = new { @class = "form-control" } }) 
           @Html.ValidationMessageFor(model => model.Cost, "", new { @class = "text-danger" }) 
          </div> 
         </div> 
        </div> 
       </div> 
       <h4>Do you offer reduced membership cost part way through the year? Add details here:</h4> 
       <div class="form-group"> 
        <div class="row col-offset-md-1 col-md-11"> 
         <div class="col-md-2"> 
          @Html.LabelFor(model => model.ReducedCost, htmlAttributes: new { @class = "control-label" }) 
          <div class="input-group"> 
           <div class="input-group-addon">£</div> 
           @Html.EditorFor(model => model.ReducedCost, new { htmlAttributes = new { @class = "form-control" } }) 
           @Html.ValidationMessageFor(model => model.ReducedCost, "", new { @class = "text-danger" }) 
          </div> 
         </div> 
         <div class="col-md-2"> 
          @Html.LabelFor(model => model.ReducedDay, htmlAttributes: new { @class = "control-label" }) 
          @Html.DropDownListFor(model => model.ReducedDay, new SelectList(Model.Days, "DayId", "DayNum", 1), new { @class = "form-control" }) 
          @Html.ValidationMessageFor(model => model.ReducedDay, "", new { @class = "text-danger" }) 
         </div> 
         <div class="col-md-2"> 
          @Html.LabelFor(model => model.ReducedMonth, htmlAttributes: new { @class = "control-label" }) 
          @Html.DropDownListFor(model => model.ReducedMonth, new SelectList(Model.Months, "MonthId", "MonthName"), new { @class = "form-control" }) 
          @Html.ValidationMessageFor(model => model.ReducedMonth, "", new { @class = "text-danger" }) 
         </div> 
        </div> 
       </div> 
       <h4>Are there age restrictions for this Membership Type? Add details here:</h4> 
       <div class="form-group"> 
        <div class="row col-offset-md-1 col-md-11"> 
         <div class="col-md-2"> 
          @Html.LabelFor(model => model.MinAge, htmlAttributes: new { @class = "control-label" }) 
          @Html.EditorFor(model => model.MinAge, new { htmlAttributes = new { @class = "form-control", @Value = "1" } }) 
          @Html.ValidationMessageFor(model => model.MinAge, "", new { @class = "text-danger" }) 
         </div> 
         <div class="col-md-2"> 
          @Html.LabelFor(model => model.MaxAge, htmlAttributes: new { @class = "control-label" }) 
          @Html.EditorFor(model => model.MaxAge, new { htmlAttributes = new { @class = "form-control", @Value = "150" } }) 
          @Html.ValidationMessageFor(model => model.MaxAge, "", new { @class = "text-danger" }) 
         </div> 
        </div> 
       </div> 
       <div class="form-group"> 
        <div class=" col-md-10"> 
         <input type="submit" name="Submit" value="Save" class="btn btn-success btn-lg" /> 
        </div> 
       </div> 
      </div> 
     </div> 
    </div> 
</div> 
} 

<div> 
@Html.ActionLink("Back to Membership Types", "AddClubMembershipType", new { clubId = Model.ClubId, editMode = true }) 
</div> 

@section Scripts { 
@Scripts.Render("~/bundles/jqueryval") 
} 
+1

Сделайте сборку отладки, получите точную информацию об ошибке (полная информация об исключении, включая номер строки) – Amit

+0

Это общее исключение. Это может быть в значительной степени _anything_ в этом коде ... или в каком-то другом связанном коде. Невозможно рассказать без дополнительной информации. –

ответ

1

Это, скорее всего, потому что MembershipTypeId на вашей модели равна нулю. Я не вижу нигде в вашем представлении, где это значение привязано, и если это не так, оно не будет частью представленных данных формы и, следовательно, не будет заполнено в модели, переданной в метод контроллера HttpPost.

Наиболее распространенное решение состоит в том, чтобы добавить Html.HiddenFor(m => m.MembershipTypeId) в форму.

P.S. На самом деле бесполезно не сообщать нам, какой номер строки возник из-за ошибки.

+0

Огромное спасибо, что это было, извините, трудно сделать жизнь, забыв сказать, где была связана ошибка. –

Смежные вопросы