dropdownlist没有选择值ASP.NET MVC 4

时间:2015-02-23 03:53:06

标签: asp.net-mvc html.dropdownlistfor

我知道这个问题已在SO中提出,但我无法将此错误与此帖区分开:DropDownListFor Not Selecting Value

我没有使用ViewBag的名称和链接中的模型属性相同。

这是我在控制器中的代码:

public ActionResult Create()
    {
        ViewBag.Companies = db.Companies.ToList();
        return View();
    }

这是我在视图中的代码:

<div class="editor-field">
        @Html.DropDownListFor(model => model.ParentId, new SelectList(ViewBag.Companies, "Id", "ShortName"), "Select a Category")
        @Html.ValidationMessageFor(model => model.ParentId)
    </div>

在我的创建表单中,下拉列表生成时没有错误,但是在单击“创建”后,即使我选择了一个值,也会出现“值不能为空”的错误。

我甚至在[POST]创建动作中再次添加了ViewBag:

 [HttpPost]
    public ActionResult Create(Company company)
    {
        ViewBag.Companies = db.Companies.ToList();
        if (ModelState.IsValid)
        {
            db.Companies.AddObject(company);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(company);
    }

我不知道错误所在的位置,我是ASP.NET MVC的新手。

以下是错误日志:

enter image description here

0 个答案:

没有答案