albert albert

albert albert

  • NA
  • 524
  • 0

cascading dropDownlist

Jul 9 2012 5:33 AM
Hi Everybody,

I try to make an cascading dropdownlist of Projects and Activities:

U select in the frist dropdownlist an project and then in the second dropdownlist the assocaited activity.

For the view I have:

[code]

@model ManyToMany.Models.Hour
@{
    ViewBag.Title = "Create";
}

<h2>
    Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/SelectWeek.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/JQueryFixes.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.GetActivities.js")" type="text/javascript"></script>





<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"),null, new {id ="project"})
                         @Html.ValidationMessageFor(model=> model.Activity.Project.Name)
        </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div class="editor-label">
                       
                        @Html.LabelFor(model=> model.Activity.Name)
                    </div>
                </td>
               
                <td>
                    <div class="editor-field">
                        @Html.DropDownListFor(model => model.Activity, new SelectList(Enumerable.Empty<SelectListItem>(),"ActivityID", "Name"),null, new {id = "activity"})
                        @Html.ValidationMessageFor(model=> model.ActivityID)
        </div>
                </td>
               
            </tr>
        </table>

[/code]

The Models:

Project:

[code]
  public enum StatusProject
    {
        Ja,
        Nee
    }

    public class Project
    {
        //[DatabaseGenerated(DatabaseGeneratedOption.None)]
       // [Display(Name= "Number")]
        [Key]
        public int ProjectID { get; set; }
       // [Display(Name = "Naam")]
        //[Required(ErrorMessage = "Naam moet wel ingevuld worden")]
        public string Name { get; set; }
       // [StringLength(100,ErrorMessage = "U kunt niet meer dan 100 tekens invoeren!! ")]
       // [Required(ErrorMessage = "Korte beschrijving")]
        [Display(Name ="omschrijving" )]
        public string Description { get; set; }

       // [Required(ErrorMessage = "U moet wel het aantal uren opgeven")]
        [Display(Name = "Geplande uren")]
        public decimal PlannedHours { get; set; }
        [Required(ErrorMessage = "eh, prijskaartje?")]
        [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 IEnumerable<Activity> Activities { get; set; }
        //public IEnumerable<SelectListItem> Activities { get; set; }

        public Project()
        {
            this.Employees = new List<Employee>();
       
        }


    }
[/code]

Class: Activity:

[code]
 public class Activity
    {
        //[Key]
        //[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        //[Display(Name = "Nummer(willekeurig nummer)")]
        //[Key]
        public int ActivityID { get; set; }
        [Required(ErrorMessage = "Naam moet wel ingevuld worden")]
        [MaxLength(50)]
        [Display(Name = "Activiteit")]
        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 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
   



        //[HttpPost]
        //Restricting an action: u also can write: [httpPost]. But then the second dropdownlist doesent work
        //[AcceptVerbs(HttpVerbs.Post)]
        [AcceptVerbs( HttpVerbs.Get)]
        public  JsonResult GetProjectList(string id)
        {
            var ProjectList = this.GetProjects(Convert.ToInt32(id));
            //DropdownList always have to get an text and Value
            var myData = ProjectList.Select(p => new SelectListItem
                                                     {
                                                         Text = p.Name,
                                                         Value = p.ActivityID.ToString(CultureInfo.InvariantCulture)
                                                        
                                                     });
           //JSonRequestBehavior is an security issur. It is protecting against invalid data.
            return Json(myData, JsonRequestBehavior.AllowGet);
        }//end method

        //This is for the second dropdownlist: the activities. When a project is selected. The Id of the selected project
        //correspond with the associated Activities.
        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)
        {
            //Activity temp = new Activity();
            //temp = GetProjects(1).FirstOrDefault();
            //hour.Activity = temp;
            //hour.ActivityID = temp.ActivityID;

            try
            {
                if (ModelState.IsValid)
                {
                    if (db.Hours != null) 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("Cant commit to database!! U forgot something??",hour.Activity.ActivityID.ToString());
                ModelState.AddModelError("",hour.Activity.Project.ProjectID.ToString(CultureInfo.InvariantCulture));
                ModelState.AddModelError("",  ViewBag.Projects = db.Projects.ToList().ToString());
               // ModelState.AddModelError("", hour.Activity.ActivityID.ToString());
                ModelState.AddModelError("", ViewBag.Activities = db.Activities.ToList().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");

            //Important!! This will mangage that the actuall data will be saved.If u forget this then u only see it in the view!!
          
                ViewBag.Projects = db.Projects.ToList();
                ViewBag.Activities = db.Activities.ToList();
            

           
           
            return View(hour);
        }//end method
       
        //
        // GET: /Hour/Edit/5
 
        public ActionResult Edit(int id)
        {
            Hour hour = db.Hours.Find(id);
            ModelState.AddModelError("Name", "What a nice name");
            //ViewBag.WeekID = new SelectList(db.Weeks, "WeekID", "WeekID", hour.WeekID);
            return View(hour);
        }//end method

        //
        // POST: /Hour/Edit/5
[/code]

So I can select an project and an associated activity. But if I try then to commit it to the database.

I get on this line(method ActionResult Create):

 if (ModelState.IsValid) the error: ModelState.IsValid = false.

THX for helping