ASP.NET MVC创建和编辑一对多关系无效的模型状态

时间:2013-04-23 20:20:50

标签: asp.net-mvc entity-framework ef-code-first one-to-many modelstate

为什么ModelState.IsValid在使用帖子存储一个到多个数据时返回“false”。我正在使用ViewModel和EditorTemplate来显示那些正在编辑的数据。在我的情况下测试(一) - 问题(很多)。如果只存储test,那么modelstate是有效的,但是如果我在测试中存储问题,模型状态就会变得无效......在整个地方查找信息,但是无法理解为什么这是无效的。由于许多教程显示这是映射一对多关系的方式,为什么我不能以这种方式发布数据?

模型

public class Test
{
   public Test()
   {
      this.Questions = new List<Question>();
   }
//some excluded for brevity

    [Required]
    public string Name { get; set; }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public DateTime TestDate { get; set; }

    public int TestTypeId { get; set; }

    public virtual ICollection<Question> Questions { get; set; }
    public virtual Type Type { get; set; }
   }
}

public class Question
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int QuestionID { get; set; }

    public int TestID { get; set; }

    public string Question { get; set; }

    public virtual Test Test { get; set; }
}

ViewModel(使用viewmodel,因为它有助于从存储在数据库中的数据生成下拉列表)

  public class TestData
{
    public Test Test { get; set; }
    public Question Question { get; set; }
    public IEnumerable<TestType> TestTypes { get; set; }
    public List<string> Questions { get; set; }
}

问题的编辑模板

@model Project.Models.CustomQuestion
<div>
 @Html.HiddenFor(a => a.QuestionID)
 @Html.HiddenFor(a => a.TestID)
 @Html.HiddenFor(a => a.Test)
 @Html.EditorFor(a => a.Question)
</div>

查看(编辑)

@model  Project.ViewModels.TestData

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

<fieldset>
    <legend>Event</legend>

    @Html.HiddenFor(a => a.Test.Id)

    <div class="editor-field">
        @Html.EditorFor(model => model.Test.Name
    </div>

    <div class="editor-field">
        @Html.EditorFor(model => model.Test.TestDate)
    </div>

    <div>
        @Html.DropDownListFor(model => model.Test.TestTypeId, new SelectList(Model.TestTypes, "Id", "Name"))
    </div>

    <div class="editor-field">
        if 5 questions are stored 5 textboxes with questions will appear
        @Html.EditorFor(model => model.Test.Questions)
    </div>

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

控制器

    public ActionResult Edit(int id = 0)
    {

       var viewModel = new ViewModels.TestData
       {
          Test = db.Tests.Find(id),
          TestTypes = db.TestTypes
       };
           return View(viewModel);
    }

    [HttpPost]
    public ActionResult Edit(TestData testData)
    {

       if (ModelState.IsValid) //returns "false" if testData.Event.Questions > 0
       {
          db.Entry(testtData).State = EntityState.Modified;
          db.SaveChanges();
          return RedirectToAction("Index");
       }

       return View(testData);
     }

0 个答案:

没有答案