控制器中模型的null对象引用

时间:2015-04-13 15:33:42

标签: c# asp.net asp.net-mvc asp.net-mvc-4

在asp.net mvc4应用程序中,我得到了" cond"的空引用。在动作编辑(Models.BigModel BigModel)中。我无法确定问题所在。视图很好,数据显示在数据库中,但是当我需要保存我遇到问题的更改时。

控制器:

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);
}

这是模特:

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; }
    }
}

这是我的数据库:

regle(int:id,string:action)

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

来自regle的

id_regle外键

以下是观点:

@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")
}

请提出任何建议

1 个答案:

答案 0 :(得分:0)

在View中使用for循环收集,否则它将在行动中发布为null

@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>
  }