I am using @Html.DropDownListFor
for the first time. Code is below.
Model:
class Student
{
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
[Required]
[Display(Name = "Roll Number")]
public string RollNumber { get; set; }
[Required]
[Display(Name = "ClassId")]
public int ClassId { get; set; }
}
class Class
{
[Required]
[Display(Name = "ClassId")]
public string RollNumber { get; set; }
[Required]
[Display(Name = "ClassName")]
public string RollNumber { get; set; }
}
Controller:
public ActionResult Create()
{
Student student = new BusinessEntities.Student();
List<Class> classes = GetAllClasses();
ViewBag.ClassId = new SelectList(classes, "ClassId", "ClassName");
return View(student);
}
[HttpPost]
public ActionResult Create(BusinessEntities.Student student)
{
if (ModelState.IsValid)
{
//Integer has 0 by default. But in our case if it contains 0,
//means no class selected by user
if(student.ClassId==0)
{
ModelState.AddModelError("ClassId", "Select Class to Enroll in");
return View(student);
}
}
}
Student Create View:
<form method="post">
Select Class :
@Html.DropDownListFor(Model=>Model.ClassId,ViewBag.ClassId as IEnumerable<SelectListItem>, "ClassId","ClassName")
@Html.ValidationMessageFor(Model => Model.ClassId)
<input type="submit" value="Submit" />
</form>
Error Message:
The ViewData item that has the key 'ClassId' is of type 'System.Collections.Generic.List`1[[BusinessEntities.Class, BusinessEntities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' but must be of type 'IEnumerable'.
I want ClassId
of Student
be binded and populated automatically when posted back to Controller. Please help me to get rid of it.
Thanks.
You need to give the
SelectList
a different name that the property your binding to (say)and then
and then ensure if you return the view (for example if
ModelState
is invalid), that you repopulate theSelectList
(as you have done in the GET method). Currently when you return the view, it isnull
resulting in an error, because if the second parameter isnull
the fallback is that the helper expects the first parameter to beIEnumerable<SelectListItem>
(but its not - its typeofint
)Side notes: Do not use
Model => Model.XXX
(capital M) and your current use ofDropDownistFor()
as 2 parameters which make no sense."ClassId"
will add a label option<option value="">ClassId</option>
and the last one,"ClassName"
will not do anything.Edit
In addition, your
is a bit pointless.
student.ClassId
will never be0
unless one of the items in yourGetAllClasses()
hasClassId = 0
. You should be usingand in the view
which will create the first option with a value of
null
. If this option were selected, then theDefaultModelBinder
will attempt to set the value ofClassId = null
which fails (because typeofint
cannot benull
) and aModelState
error is added andModelState
becomes invalid.The in the POST method