Проблема с Edit View с использованием ViewModel - PullRequest
0 голосов
/ 19 сентября 2011

У меня есть сложный объект, который я хочу использовать в режиме редактирования. Чтобы упростить вещи, я создал ViewModel и успешно создал страницу представления редактирования, и все отображается правильно. Когда я нажимаю «Сохранить», все разваливается.

ViewModel выглядит следующим образом:

public class ClosureEditViewModel
{

    public Model.Closure Closure { get; set; }
    public Model.School School { get; set; }
    public Model.ClosureDetail CurrentDetails { get; set; }
}

Часть представления выглядит следующим образом:

<div class="display-label">School</div>
<div class="display-field">
    @Html.DisplayFor(model => model.Closure.School.Name)
</div>
<div class="display-label">Closed</div>
<div class="display-field">
    @Html.DisplayFor(model => model.Closure.Logged)
</div>
....
<div class="editor-label">
    @Html.LabelFor(model => model.CurrentDetails.DateOpening, "Date Opening (dd/mm/yyyy)")
</div>
<div class="editor-field">
    @Html.TextBox("DateOpening", Model.CurrentDetails.DateOpening.ToString("dd/MM/yyyy"))
    @Html.ValidationMessageFor(model => model.CurrentDetails.DateOpening)
</div>
....
    <tr>
        <td>
            @Html.CheckBoxFor(model => model.CurrentDetails.Nursery, (Model.School.Nursery ? null : new { @disabled = "disabled" }))
        </td>

Важными частями контроллера являются следующие:

    public ActionResult Edit(int id)
    {
        Data.IClosureReasonRepository reasonRepository = new Data.SqlServer.Repositories.ClosureReasonRepository(UnitOfWork);
        IEnumerable<Model.ClosureReason> reasons = reasonRepository.GetAll();

        Model.Closure closure = ClosureRepository.GetClosure(id);
        Model.ClosureDetail currentDetail = closure.ClosureDetails.Last();
        ViewModels.ClosureEditViewModel editClosure = new ViewModels.ClosureEditViewModel() { Closure = closure, School = closure.School, CurrentDetails = closure.ClosureDetails.Last() };
        ViewBag.ReasonId = new SelectList(reasons, "Id", "Name", currentDetail.ReasonId);
        return View(editClosure);
    }

    [HttpPost]
    public ActionResult Edit(ViewModels.ClosureEditViewModel newDetail)
    {
        //if (ModelState.IsValid)
        //{

        //}

        Data.IClosureReasonRepository reasonRepository = new Data.SqlServer.Repositories.ClosureReasonRepository(UnitOfWork);
        IEnumerable<Model.ClosureReason> reasons = reasonRepository.GetAll();
        ViewBag.ReasonId = new SelectList(reasons, "Id", "Name", newDetail.CurrentDetails.ReasonId);
        return View(newDetail);
    }

Когда я нажимаю сохранить, появляется следующее сообщение:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 94:                 </td>
Line 95:                 <td>
Line 96:                     @Html.CheckBoxFor(model => model.CurrentDetails.P1, (Model.School.P1 ? null : new { @disabled = "disabled" }))
Line 97:                 </td>
Line 98:                 <td>

Я просто не могу понять, почему у него проблемы с имуществом школы, но ни с одним из двух других.

Джеймс: -)

1 Ответ

1 голос
/ 19 сентября 2011

Кажется, что Model.School равно нулю, когда вы снова визуализируете представление в действии POST. Убедитесь, что оно не равно нулю, поскольку, по вашему мнению, у вас нет единственного поля ввода, связанного с School property =>, это свойство будет нулевым внутри действия вашего контроллера POST.

[HttpPost]
public ActionResult Edit(ClosureEditViewModel viewModel)
{
    ... some operations

    // Make sure that viewModel.School is not null
    // Remember that the checkbox is bound to CurrentDetails.P1 so 
    // when you post to this action there is nothing that will initialize
    // the School property => you should do whatever you did in your GET
    // action in order to initialize this property before returning the view
    return View(viewModel);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...