albert albert

albert albert

  • NA
  • 524
  • 0

error with dropdownlist

Jul 4 2012 7:39 AM
Hi everybody,

I have this:
Models:
[code]
 public class Project
    {
        //[DatabaseGenerated(DatabaseGeneratedOption.None)]
       // [Display(Name= "Number")]
        [Key]
        public int ProjectID { get; set; }
        [Display(Name = "Naam")]
        public string Name { get; set; }
        [StringLength(100,ErrorMessage = "U kunt niet meer dan 100 tekens invoeren!! ")]
        [Display(Name ="omschrijving" )]
        public string Description { get; set; }

        [Display(Name = "Geplande uren")]
        public decimal PlannedHours { get; set; }
         [DisplayFormat(DataFormatString = "{0:c}")]
        [Display(Name = "Prijs")]
        public decimal price { get; set; }
        public bool Intern { get; set; }
        [Display(Name = "project manager")]
        public string projectManager { get; set; }
        [Display(Name = "Project Code")]
        public string projectCode { get; set; }
        [Display(Name = "Start Datum")]
        public DateTime? StartDate { get; set; }
        [Display(Name = "Eind datum")]
        public DateTime? EndDate { get; set; }
        [Display(Name = "Actief?")]
        public bool Active { get; set; }
       // public StatusProject StatusProject { get; set; }

        public virtual ICollection<Employee> Employees { get; set;}
        public virtual ICollection<Activity>Acitivity  { get; set; }
        public Project()
        {
            this.Employees = new List<Employee>();
       
        }


    }
[/code]

and class activity:

[code]
 public class Activity
    {
        //[Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [Display(Name = "Nummer(willekeurig nummer)")]
        public int ActivityID { get; set; }

        [MaxLength(50),Required(ErrorMessage="Naam moet wel ingevuld worden")]
        [Display(Name = "Naam")]
        public string Name { get; set; }

        [Display(Name = "Omschrijving")]
        public string Description { get; set; }

        [Display(Name = "uren")]
        public decimal Hour { get; set; }
       
        [DataType(DataType.Date)]
        [Display(Name = "Begin datum")]
        public DateTime BeginDate { get; set; }       
       
        [DataType(DataType.Date)]
        [Display(Name = "Eind datum")]
        public DateTime EndDate { get; set; }

        [Display(Name = "Tarief")]
        public decimal Tariff { get; set; }

        [Display(Name = "Actief?")]
        public bool Active { get; set; }
       
        [Display(Name = "project")]
        public int ProjectID { get; set; }
        //public virtual DbSet<Project> Project { get; set; }
        public virtual Project Project { get; set; }
        public virtual ICollection<Employee> Employee { get; set; }
        public virtual ICollection<Activity> Activities { get; set; }
        public virtual ICollection<Hour> Hours { get; set; }

    }
[/code]

and for the controller:

[code]
 public class HourController : Controller
    {
        private TimeSheetContext db = new TimeSheetContext();


        /*
        public ActionResult Index(ActivityFilter filter)
        {
           
            if(filter == null)
            {
                filter = new ActivityFilter();
            }
            return View(filter);
        }
         */

        /*
        public ActionResult ProjectsAndactivitys()
        {
            var viewModel = new Hour();
            viewModel.Activity.Project = db.Projects;
            return View(viewModel);

        }
         */

        //public  JsonResult Projects(int? id)
       // {
        //    return Json(new {items = ActivityFilter.GetActivities(id)}, JsonRequestBehavior.AllowGet);
        //}//end method
       

        //
        // GET: /Hour/

        public ViewResult Index()
        {
           
            //var hours = db.Hours.Include(h => h.Week);
           // return View(hours.ToList());
            //ViewBag.Projects = db.Projects.ToList();
          //  ViewBag.Activities = db.Activities.ToList();

            var Hours = db.Hours.Include(a => a.Activity).Include(a => a.Activity.Project);
            return View(db.Hours.ToList());
        }

       
        [HttpPost]
        public  ActionResult Index(int year)
        {

            return new EmptyResult();
        }
        /*
        public ActionResult WikiDetails(bool editable)
        {
            //Wiki wiki = new Wiki
            Wiki wiki = new Wiki
            {
                Name =  "Hallo",
                Url =  "hallo.com",
                Editable = editable             

            };
            return View(wiki);
        }
         */
         
        //
        // GET: /Hour/Details/5

        public ViewResult Details(int id)
        {
            Hour hour = db.Hours.Find(id);
            return View(hour);
        }

        //
        // GET: /Hour/Create

        public ActionResult Create()
        {
            //ViewBag.WeekID = new SelectList(db.Weeks, "WeekID", "WeekID");
            //ViewBag.weeknr = new SelectList( "weeknr", "value");
            //var query = db.Activities.Select(c => new {c.ActivityID, c.Name});
           // ViewBag.Activities = new SelectList(query.AsEnumerable(), "ActivityID", "Name");
            ViewBag.HourID = new SelectList(db.Hours, "HourID", "HourID");
            //ViewBag.ProjectID = new SelectList(db.Projects, "ProjectID", "Name");
            //ViewBag.ActivityID = new SelectList(query.AsEnumerable(), "ActivityID", "Name", 2);
           // ViewBag.ActivityID = new SelectList(db.Activities, "ActivityID", "Name");
            ViewBag.Projects = db.Projects.ToList();
            ViewBag.Activities = db.Activities.ToList();

            /*
            IEnumerable<SelectListItem> items = db.Activities
               .Select(c => new SelectListItem
                                 {
                                     Value = c.ActivityID.ToString(CultureInfo.InvariantCulture),
                                     Text = c.Name

                                 });
            ViewBag.Activities = items;
             */
            return View(new Hour());
        }//end method create

        [AcceptVerbs(HttpVerbs.Get)]
        public  JsonResult GetProjectList(string id)
        {
            var ProjectList = this.GetProjects(Convert.ToInt32(id));
            var myData = ProjectList.Select(p => new SelectListItem
                                                     {
                                                         Text = p.Name,
                                                         Value = p.ActivityID.ToString(CultureInfo.InvariantCulture)
                                                        
                                                     });
            return Json(myData, JsonRequestBehavior.AllowGet);
        }//end method

        private  IEnumerable<Activity> GetProjects(int id)
        {
            //List of activities corresponding with the selected Project
            return db.Activities.Where(p => p.ProjectID == id).ToList();

        }//end method

            //
        // POST: /Hour/Create

        [HttpPost]
        public ActionResult Create(Hour hour)
        {

            try
            {
                if (ModelState.IsValid)
                {
                    db.Hours.Add(hour);

                    //db.Hours.Add(hour.Monday.Value.ToString("d"));
                   
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException)
            {
                    //ModelState.AddModelError("",hour.Monday.Value.ToShortDateString());
                ModelState.AddModelError("", hour.HourID.ToString());
                ModelState.AddModelError("",hour.Activity.ActivityID.ToString());
                ModelState.AddModelError("",hour.Activity.Project.ProjectID.ToString());
              
            }//end catch exception.
           

            //ViewBag.WeekID = new SelectList (db.Weeks, "Monday", "Monday", hour.WeekID);
           // ViewBag.weeknr = new SelectList( "weeknr", "txtBox");
            //ViewBag.HourID = new SelectList(db.Hours, "txtBox", "Monday");
            return View(hour);
        }//end method
[/code]

and the view:

[code]


<script type="text/javascript">
    $(document).ready(function () {
        $("#project").change(function () {
            var idDept = $(this).val();
            $.getJSON('@Url.Action("GetProjectList", "Hour")', { id: idDept },
                    function (myData) {
                        var select = $("#activity");
                        select.empty();
                        select.append($('<option/>', {
                            value: 0,
                            text: "choose"
                        }));
                        $.each(myData, function (index, itemData) {
                            select.append($('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));
                        });
                    });
        });
    });
</script>



@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Hour</legend>
       
       
        <table style="width: 10%;">
            <tr>
                <td>
                    <div class="editor-label">
                        @Html.LabelFor(model=> model.Activity.ProjectID,"Project")
                    </div>
                </td>
                <td>
                     <div class="editor-field">
                         @Html.DropDownListFor(model => model.Activity.Project.ProjectID, new SelectList(ViewBag.Projects as IEnumerable,"ProjectID","Name"),"Select", new {id ="project"})
                         @Html.ValidationMessageFor(model=> model.Activity.Project.Name)
        </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div class="editor-label">
                       
                        @Html.LabelFor(model=> model.ActivityID,"Activity")
                    </div>
                </td>
               
                <td>
                    <div class="editor-field">
            @Html.DropDownListFor(model => model.Activity, new SelectList(Enumerable.Empty<SelectListItem>(),"ActivityID", "Name"),"Select", new {id = "activity"})
            @Html.ValidationMessageFor(model=> model.ActivityID)
        </div>
                </td>
               
            </tr>
        </table>

[/code]

but when I now press the save button after I selected an project and an associated activity I get this error:

Server Error in '/' Application.

Value cannot be null.
Parameter name: items

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.ArgumentNullException: Value cannot be null.
Parameter name: items

Source Error:

Line 65:                 <td> Line 66:                      <div class="editor-field"> Line 67:                          @Html.DropDownListFor(model => model.Activity.Project.ProjectID, new SelectList(ViewBag.Projects as IEnumerable,"ProjectID","Name"),"Select", new {id ="project"})  Line 68:                          @Html.ValidationMessageFor(model=> model.Activity.Project.Name) Line 69:         </div>

Source File: f:\projects18-06-2012\ManyToMany26-05-2012WorkingVersionWorkingVersion03\ManyToMany\Views\Hour\Create.cshtml    Line: 67