Hello,
I have interrelated tables, Students has one to many relation with Enrollment, while Enroll further has relations with Institution, Session , Class and Section Tables, I created a ViewModel StudentVM
and wanted to insert data in Student table as well as Enrollment.
When I enter data in form and submit then it works ok.
but when I submit blank and leave some required fields I get this error. the Error is below
Server Error in '/' Application.
The ViewData item that has the key 'InstitutionID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The ViewData item that has the key 'InstitutionID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
Source Error:
Line 19: @Html.Label("Institution", htmlAttributes: new { @class = "control-label col-md-2" })
Line 20: <div class="col-md-10">
Line 21: @Html.DropDownList("InstitutionID", ViewBag.InstitutionID as SelectList, "-Select Institution-", new { @class = "form-control" } )
Line 22: </div>
Line 23: </div>
Source File: D:\Projects\ASP.net\MVC\School Management\SchoolMVC\SchoolMVC\Views\Students\Create.cshtml Line: 21
Stack Trace:
[InvalidOperationException: The ViewData item that has the key 'InstitutionID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.]
System.Web.Mvc.Html.SelectExtensions.GetSelectData(HtmlHelper htmlHelper, String name) +355
System.Web.Mvc.Html.SelectExtensions.SelectInternal(HtmlHelper htmlHelper, ModelMetadata metadata, String optionLabel, String name, IEnumerable`1 selectList, Boolean allowMultiple, IDictionary`2 htmlAttributes) +118
System.Web.Mvc.Html.SelectExtensions.DropDownList(HtmlHelper htmlHelper, String name, IEnumerable`1 selectList, String optionLabel, Object htmlAttributes) +38
ASP._Page_Views_Students_Create_cshtml.Execute() in D:\Projects\ASP.net\MVC\School Management\SchoolMVC\SchoolMVC\Views\Students\Create.cshtml:21
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9836613
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
What I have tried:
view Model is:
namespace SchoolMVC.Models.ViewModel
{
public class StudentsVM
{
public int StudentID { get; set; }
[Required(ErrorMessage = "Admission number is required.")]
public string AdmissionNo { get; set; }
public string awrno { get; set; }
public string boardregno { get; set; }
[Required(ErrorMessage = "Student Name is required.")]
public string StudentName { get; set; }
[Required(ErrorMessage = "Father Name is required.")]
public string FatherName { get; set; }
public string MotherName { get; set; }
public string FatherCNO { get; set; }
public string FatherCNIC { get; set; }
public string PermanentAddress { get; set; }
public string TemporaryAddress { get; set; }
public string ContactNo { get; set; }
public string EmailID { get; set; }
public Nullable<System.DateTime> DOB { get; set; }
public string Gender { get; set; }
public Nullable<System.DateTime> AdmissionDate { get; set; }
public string Religion { get; set; }
public byte[] Photo { get; set; }
public string Nationality { get; set; }
public string LastSchoolAttended { get; set; }
public string Result { get; set; }
public string PassPercentage { get; set; }
public string House { get; set; }
public string AccountNo { get; set; }
public string AccountName { get; set; }
public string Bank { get; set; }
public string Branch { get; set; }
public string IBANCode { get; set; }
public int EnrollID { get; set; }
public int InstitutionID { get; set; }
public int SessionID { get; set; }
public int ClassID { get; set; }
public int SectionID { get; set; }
}
}
And my Create Get and Post Methods are as below:
public ActionResult Create()
{
ViewBag.ClassID = new SelectList(db.tblClasses, "ClassID", "ClassName");
ViewBag.InstitutionID = new SelectList(db.tblInstitutes, "InstitutionID", "Institution");
ViewBag.SessionID = new SelectList(db.tblSessions, "SessionID", "SessionName");
return View();
}
// POST: Students/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create( StudentsVM Student)
{
if (ModelState.IsValid)
{
tblStudent st = new tblStudent();
st.StudentName = Student.StudentName;
st.FatherName = Student.FatherName;
st.AdmissionNo = Student.AdmissionNo;
db.tblStudents.Add(st);
db.SaveChanges();
// InsertEnrollmet(Student);
var stuID = st.StudentID;
tblEnrollment en = new tblEnrollment();
en.StudentID = stuID;
en.InstitutionID = Student.InstitutionID;
en.SessionID = Student.SessionID;
en.ClassID = Student.ClassID;
en.SectionID = Student.SectionID;
db.tblEnrollments.Add(en);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ClassID = new SelectList(db.tblClasses, "ClassID", "ClassName");
ViewBag.InstitutionID = new SelectList(db.tblInstitutes, "InstitutionID", "Institution");
ViewBag.SessionID = new SelectList(db.tblSessions, "SessionID", "SessionName");
return View(Student);
}
In View it is like below
<div class="form-group">
@Html.Label("Institution", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("InstitutionID", (IEnumerable<SelectListItem>) ViewData["InstitutionID"] as SelectList , "-Select Institution-", new { @class = "form-control" } )
@Html.ValidationMessageFor(model => model.InstitutionID, "", new { @class = "text-danger" })
</div>
</div>