Abir BY Abir BY - 3 months ago 10
ASP.NET (C#) Question

null object reference of model in controller

In asp.net mvc4 app, I get a null reference of "cond" in the action Edit(Models.BigModel BigModel). I can't figure where the problem is. The view is fine, data is displayed from the database, but when I need to save the changes that's where I get the problem.

Controller:

public ActionResult Edit(int id = 0)
{
Models.BigModel BigModel = new Models.BigModel();
BigModel.regle = db.regle.Single(r => r.id == id);
BigModel.cond = db.cond.Where(c => c.id_regle == id);

//regle regle = db.regle.Single(r => r.id == id);
if (BigModel.regle == null)
{
return HttpNotFound();
}
return View(BigModel);
}

//
// POST: /Default1/Edit/5

[HttpPost]
public ActionResult Edit(Models.BigModel BigModel)
{
if (ModelState.IsValid)
{
db.regle.Attach(BigModel.regle);
db.ObjectStateManager.ChangeObjectState(BigModel.regle, EntityState.Modified);
foreach (var c in BigModel.cond) //this is where I get the error, cond is null
{
db.cond.Attach(c);
}
db.ObjectStateManager.ChangeObjectState(BigModel.cond, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(BigModel);
}


This is the Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication3.Models
{
public class BigModel
{
public regle regle { get; set; }
public IQueryable<cond> cond { get; set; }
}
}


This is my data base:

regle( int: id, string:action)

cond(int: id_cond, string: cond_txt, int:id_regle)

id_regle foreign key from regle

And here is the view:

@model MvcApplication3.Models.BigModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
<legend>regle</legend>

@Html.HiddenFor(model => model.regle.id)

<div class="editor-label">
@Html.LabelFor(model => model.regle.action)
@Html.EditorFor(model => model.regle.action)
@Html.ValidationMessageFor(model => model.regle.action)

</div>
<div class="editor-field">
@Html.LabelFor(model => model.cond)


@foreach (var item in Model.cond)
{
<tr>
<td>
@Html.EditorFor(modelItem => item.cond_txt)
@Html.ValidationMessageFor(modelItem => item.cond_txt)
</td>
<td>
&nbsp;&nbsp;&nbsp;
</td>
</tr>
}
@Html.ValidationMessageFor(model => model.cond)
</div>

<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}


Any suggestions please

Answer

Use for loop for Collections in View otherwise it will be posted null in action

@for (int i=0; i < Model.cond.Count; i++)
  {
      <tr>
        <td>
         @Html.EditorFor(modelItem => Model.cond[i].cond_txt)
         @Html.ValidationMessageFor(modelItem => Model.cond[i].cond_txt)
        </td>
        <td>
        &nbsp;&nbsp;&nbsp;
        </td>
      </tr>
  }
Comments