简体   繁体   中英

DropDownList Error, System.InvalidOperationException

Create.cshtml

@Html.DropDownList("KategoriId",null,htmlAttributes: new { @class="form-control"})

MakaleController.cs

public ActionResult Create()
        {
            ViewBag.KategoriId = new SelectList(db.Kategoris, "KategoriId", "KategoriAdi");
            return View();
        }

but it's say When I make a post request,

The ViewData element with the 'KategoriId' key is of type 'System.Int32', but of type 'IEnumerable '.

How to fix this error, I tried many ways but it did not happen. He says that the value is generally null.

Kategori.cs (!! NOT KATEGORIS, i create with code first)

[Table("Kategori")]
    public partial class Kategori
    {
        public int KategoriId { get; set; }

        [StringLength(50)]
        public string KategoriAdi { get; set; }

        public virtual Makale Makale { get; set; }
    }

Updated Your dropdown definition is not right

it should look like below

@Html.DropDownListFor(m => m.CategoryID, Model.CategoryList, "-Please select-")

you pass null to Dropdownlist, but it is supposed to be at least an empty list You also try to keep dropdownlist data in viewbag. it is supposed to be a List property in the view model. PS: using native words in variable names are not acceptable in global projects due to readability issues =)

PS: You can check a similar question and answer from here The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM