0

我正在尝试获取一个下拉列表,以将其在 HTTP POST 上的选择连同其他相关数据一起发回。我可以看到表单集合中的值,但是当我查看其他发布的实体时,VS2010 告诉我该对象为 NULL。

该模型具有多对一关系:

[Key]
public int ProgramTypeId { get; set; }

public string ProgramType { get; set; }

public List<SurveyProgramModels> SurveyProgramModel { get; set; }

该模型使用 ProgramTypeId 作为外键

public class SurveyProgramModels
    {
        [Key]
        public Guid ProgramId { get; set; }

        public virtual SurveyProgramTypeModels SurveyProgramTypeModels { get; set; }

        public int ProgramYear { get; set; }

        public int ProgramStatus { get; set; }

    }

控制器 GET/POST

  //
        // GET: /SurveyProgram/Create

        public ActionResult Create()
        {

            SelectList typelist = new SelectList(db.SurveyProgramTypeModels.ToList(), "ProgramTypeId", "ProgramType", db.SurveyProgramTypeModels);
            ViewData["SurveyProgramTypeModels"] = typelist;

            return View();
        } 

        //
        // POST: /SurveyProgram/Create

        [HttpPost]
        public ActionResult Create(SurveyProgramModels surveyprogram, FormCollection collection)
        {


            SelectList typelist = new SelectList(db.SurveyProgramTypeModels.ToList(), "ProgramTypeId", "ProgramType", db.SurveyProgramTypeModels);
            ViewData["SurveyProgramTypeModels"] = typelist;

          //  int SelectedCollection = Int32.Parse(collection["ProgramTypeId"]);

            if (ModelState.IsValid)
            {
              surveyprogram.ProgramId = Guid.NewGuid();

                db.SurveyPrograms.Add(surveyprogram);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(surveyprogram);
        }

在视图中选择列表:

<div class="editor-field">
            @Html.DropDownList("ProgramTypeTypeModels", (IEnumerable<SelectListItem>)ViewData["SurveyProgramTypeModels"])
            @Html.ValidationMessageFor(model => model.SurveyProgramTypeModels)
        </div>

选择列表在视图中呈现时是正确的,并且我可以将所选值视为表单集合的一部分。我不确定为什么所选值没有与 SurveyProgramModels 的其他数据一起保存。

编辑:当我删除两个类之间的关系时,我还应该提到正确提交的数据。

4

1 回答 1

2

表单元素被命名为“ProgramTypeTypeModels”,这将导致它无法正确绑定回来。您还应该创建一个Model返回到View.

然后将 theSelectList作为属性包含在Modelfor theView

现在您执行以下操作:

 @Html.DropDownListFor(model => model.SurveyProgramTypeModels)

然后,[HttpPost]您可以将强类型Model作为参数,并且 aspnet 绑定将完成所有工作,没有理由将 DTO 排除在外FormCollection

于 2012-06-14T14:36:55.867 回答