模型:

public class Category
{
    [Key]
    public int ID { get; set; }

    [Required(ErrorMessage = "Kategoria jest wymagana!")]
    public string Kategoria { get; set; }

    [Required(ErrorMessage = "Kod jest wymagany!")]
    public string Kod { get; set; }
}


控制器:

public ActionResult DodajPrzedmiot()
{
    if (StaticFunctions.IfLogged())
    {
        using (var db = new DatabaseContext())
        {
            var cats = from b in db.Categories
                       select new { b.Kategoria };

            var x = cats.ToList().Select(c => new SelectListItem
            {
                Text = c.Kategoria,
                Value = c.Kategoria
            }).ToList();

            //List<SelectListItem> catList = new List<SelectListItem>();
            //foreach (var t in cats)
            //{
            //    SelectListItem s = new SelectListItem();
            //    s.Text = t.ToString();
            //    s.Value = t.ToString();
            //    catList.Add(s);
            //}
            ViewBag.Kategoria = x;
        }
        return View();
    }
    else
    {
        return RedirectToAction("Logowanie", "User");
    }
}


视图:

<div class="form-group">
        @Html.LabelFor(model => model.Kategoria, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Kategoria, null)
        </div>
    </div>


问题是当我添加带有选定内容的项目时,此列表显示了我从数据库中选择的值。 “ Biurowe”类别将信息添加到数据库,但同时给我错误:


  类型“ System.InvalidOperationException”的异常发生在
  System.Web.Mvc.dll,但未在用户代码中处理
  
  附加信息:没有类型的ViewData项
  “ IEnumerable”具有键“ Kategoria”。


我应该在这里改变什么?

最佳答案

@Html.DropDownListFor(model => model.Kategoria, null)中的第二个参数应为项目列表,在您的情况下为ViewBag.Kategoria
我什至建议您使用其他名称,例如ViewBag.KategoriaList。在ViewBag中使用与绑定到DropDownList的属性相同的列表名称时,有时会遇到问题。

试试这个代码:

public ActionResult DodajPrzedmiot()
    {
        if (StaticFunctions.IfLogged())
        {
            using (var db = new DatabaseContext())
            {
                var cats = from b in db.Categories
                           select new { b.Kategoria };

                var x = cats.ToList().Select(c => new SelectListItem
                {
                    Text = c.Kategoria,
                    Value = c.Kategoria
                }).ToList();

                ViewBag.KategoriaList = x;
            }
            return View();
        }
        else
        {
            return RedirectToAction("Logowanie", "User");
        }
    }


在视图中:

<div class="form-group">
        @Html.LabelFor(model => model.Kategoria, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Kategoria, ViewBag.KategoriaList as IEnumerable<SelectListItem>)
        </div>
    </div>


您还必须在ViewBag操作中填充POST。这是您的POST操作应为:

[HttpPost]
    public ActionResult DodajPrzedmiot(Item itm)
    {
        if (ModelState.IsValid)
        {
            try
            {
                using (var db = new DatabaseContext())
                {
                    // try putting this code in a separate function and use that function in both actions to populate the ViewBag.
                    var cats = from b in db.Categories
                               select new { b.Kategoria };

                    var x = cats.ToList().Select(c => new SelectListItem
                    {
                        Text = c.Kategoria,
                        Value = c.Kategoria
                    }).ToList();

                    ViewBag.KategoriaList = x;

                    if (itm.Ilosc_zakupiona - itm.Ilosc_wypozyczona < 0) throw new ArgumentOutOfRangeException();
                    itm.Ilosc_magazynowa = itm.Ilosc_zakupiona - itm.Ilosc_wypozyczona;
                    db.Items.Add(itm);
                    db.SaveChanges();
                }
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateException)
            {
                ViewBag.ErrorMessage = "Istnieje już przedmiot o takiej nazwie i/lub kodzie!";
                return View();
            }
            catch (ArgumentOutOfRangeException)
            {
                ViewBag.ErrorMessage = "Ilość zakupiona i/lub wypożyczona nie mogą być mniejsze od zera!";
                return View();
            }
        }
        return View();
    }

10-08 09:28