Hi I am working on my own application. I set the the basic crud and when I want to create new item in database through my create form, everything goes well. Problem is when I intentionally miss something and expecting error messages. Then I have an excetion:
Quote:
The ViewData item that has the key 'CategoryID' is of type 'System.Int32' but must be of type 'IEnumerable<selectlistitem>'.
My Model:
public int JidloID { get; set; }
[Required(ErrorMessage ="název je vyžadován")]
public string name { get; set; }
public int CategoryID { get; set; }
[Required(ErrorMessage ="recept vyžadován")]
[AllowHtml]
public string recipe { get; set; }
[Required(ErrorMessage ="suroviny požadovány")]
[AllowHtml]
public string ingredients { get; set; }
public Category Category { get; set; }
Controller actions:
public ActionResult Create()
{
var categoryList = new List<SelectListItem>();
categoryList.AddRange(db.Categories
.Select(a => new SelectListItem
{
Value = a.CategoryID.ToString(),
Text = a.popis
}));
ViewBag.CategoryList = categoryList;
return View();
}
public ActionResult Add(Jidlo jidlo,int CategoryID)
{
if(ModelState.IsValid)
{
db.Jidlos.Add(jidlo);
db.SaveChanges();
return RedirectToAction("Display");
}
return View("Create", jidlo);
}
My form in the view:
@using jidloApp.Models
@using jidloApp.Classes
@model Jidlo
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@Html.ValidationSummary()
@using (Html.BeginForm("Add", "Disp", FormMethod.Post, new { @class = "form-horizontal" }))
{
<div class="form-group">
<label class="col-sm-2 control-label">Nazev</label>
<div class="col-sm-10">
@Html.TextBoxFor(x => x.name, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.name)
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Recept</label>
<div class="col-sm-10">
@Html.TextAreaFor(x => x.recipe, new { @class = "form-control formatedtext" })
@Html.ValidationMessageFor(x => x.recipe)
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Ingredience</label>
<div class="col-sm-10">
@Html.TextAreaFor(x => x.ingredients, new { @class = "form-control textarea" })
@Html.ValidationMessageFor(x => x.ingredients)
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Kategorie</label>
<div class="col-sm-10">
@Html.DropDownList("CategoryID", ViewBag.CategoryList as IEnumerable<SelectListItem>, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Pridat novy recept</button>
</div>
</div>
}
<script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script>
<script>
tinymce.init({
selector: 'textarea',
toolbar: 'fontsizeselect',
fontsize_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt'
});
</script>
Do you have some idea what to do about it?
What I have tried:
So far I have tried change selectlist.