0

我是asp.net MVC的新手,希望有人能提供帮助。我尝试将创建表单的类别字段更改为 dorpdownlist。下拉列表的项目来自一个表 - 类别

一切似乎都很好,但是当我提交创建时,我收到了错误消息

具有键“类别”的 ViewData 项的类型为“System.String”,但必须为“IEnumerable<SelectListItem>”类型

这是我的控制器代码:

 public ActionResult Create()
 {
     IEnumerable<SelectListItem> items = db.Catagorys
        .Select(c => new SelectListItem
        {

            Text = c.CatagoryName

        });

        ViewBag.Searchcategory = items;
        return View();
 } 

    //
    // POST: /Admin/Create

    [HttpPost]
    public ActionResult Create(Contact contact)
    {
        try
        {
            if (ModelState.IsValid)
            {

                db.Contacts.Add(contact);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        catch (DataException)
        {
            //Log the error (add a variable name after DataException)
            ModelState.AddModelError("", "Unable to save changes, Try again.");

        }

        return View(contact);
    }

这是我的创建视图代码:

<div class="editor-field">
    @Html.DropDownListFor(model => model.category, (IEnumerable<SelectListItem>)ViewBag.Searchcategory, "--Select One--")
    @Html.ValidationMessageFor(model => model.category)
</div>
4

1 回答 1

1

在 post 中,如果 ModelState 无效,则返回视图。但是您仅在获取请求中填写类别选择列表,您也应该在帖子中这样做

[HttpPost]
public ActionResult Create(Contact contact)
{
    try
    {
        if (ModelState.IsValid)
        {

            db.Contacts.Add(contact);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch (DataException)
    {
        //Log the error (add a variable name after DataException)
        ModelState.AddModelError("", "Unable to save changes, Try again.");

    }

    IEnumerable<SelectListItem> items = db.Catagorys
    .Select(c => new SelectListItem
    {

        Text = c.CatagoryName

    });

    return View(contact);
}

当然,如果你创建CreateContactViewModel类,里面有 selectlist 属性,那就太好了。并摆脱使用 ViewBag

于 2013-07-12T06:09:19.980 回答