MVC DropDownListFor编辑模态不返回SelectedValue

时间:2019-03-17 06:01:17

标签: c# .net model-view-controller

我的编辑模式弹出窗口中有一个DropDownListFor字段,它是局部视图。我的模型中的Type字段是一个int。我禁用了该字段,因为我不希望用户能够编辑该字段。

<div class="form-group">
   @Html.LabelFor(model => model.Type)
   <div class="col-md-10">
      @Html.DropDownListFor(model => model.Type, ViewData["TypeList"] as IEnumerable<SelectListItem>, new { @disabled = "disabled" })
      @Html.HiddenFor(model => model.Type)
   </div>
</div>

通过JsonResult返回值和JQuery的组合来填充Edit数据。

<script type="text/javascript">
    function showModalEdit(learningObjectId) {
        $.ajax(
            {
                url: '@Url.Action("Edit")/' + learningObjectId,
                //context: JSON.stringify({ id: moduleId })
            })
            .done(function (data) {
                if (data.LearningObject && data.LearningObject.Name) {
                    document.getElementById("LearningObjectID").value = learningObjectId;
                    document.getElementById("Name").value = data.LearningObject.Name;
                    document.getElementById("DisplayName").value = data.LearningObject.DisplayName;
                    document.getElementById("Description").value = data.LearningObject.Description;
                    document.getElementById("Type").value = data.LearningObject.TypeCode;
                    document.getElementById("ImportID").value = data.LearningObject.ImportID;

                    for (var i = 0; i < data.Tags.length; i++) {
                        addTag('Tags', 'tagInputEdit', 'tagListEdit', 'tagCountEdit', data.Tags[i].Name);
                    }
                }
            });
    }
</script>

public JsonResult Edit(int? id)
{
      LearningObject learningObject = _db.LearningObjects.Find(id);
      var tags = (from t in _db.Tags
                  join lot in _db.LearningObjectTags on t.TagID equals lot.TagID
                  where lot.LearningObjectID == id.Value && lot.Active == true
                  select new { Name = t.Name }).ToList();

       return Json(new { LearningObject = learningObject, Tags = tags }, JsonRequestBehavior.AllowGet);
}

在进行研究时,我读到将禁用的DropDownListFor的值返回给Controller的最佳方法是通过一个隐藏字段,该字段在我的局部视图中实现。当我单击“编辑”模态时,正确的值将显示在禁用的DropDownListFor中,但是当我提交表单时,模型将返回值为0的控制器。

有人能看到为什么会这样吗?

0 个答案:

没有答案