HI everybody,
I try to make an cascading dropdownlist of projects and Activity
I have this:
Model:
Hour:
[code]
public class Hour
{
public int HourID { get; set; }
// public virtual Week Week { get; set; }
public int? WeekID { get; set; }
//[Key]
public int? ActivityID { get; set; }
public virtual Activity Activity { get; set; }
//public int ActivtityID { get; set; }
// public Project Project { get; set; }
//[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString="{0:c}")]
//public decimal? Amount { get; set; }
[ReadOnly(true)]
//[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public decimal HourTotal { get { return GetTotalHours(); } }
public int WeekNumber { get; set; }
public int yearNumber { get; set; }
//Properties days:
public DayOfWeek DayWeek { get; set; }
//public DateTime DateDay { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime? Monday { get; set; }
public int Days { get; set; }
[DataType(DataType.Date)]//
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime? Tuesday { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime? Wendsday { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime? Thursday { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime? Fryday { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime? Saterday { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime? Sunday { get; set; }
//End properties days
//Properties hours:
// [DisplayFormat(DataFormatString = "{0:#.##0.0#}", ApplyFormatInEditMode = true)]
[Required]
//[DisplayFormat(DataFormatString= "{0:#,##0.000#}")]
public Decimal MondayHours { get; set; }
//[DisplayFormat(DataFormatString = "{0:#.#}", ApplyFormatInEditMode = true)]
[Required]
public Decimal TuesdayHours { get; set; }
//[DisplayFormat(DataFormatString = "{0:#.#}", ApplyFormatInEditMode = true)]
[Required]
public Decimal WendsdayHours { get; set; }
//[DisplayFormat(DataFormatString = "{0:#.#}", ApplyFormatInEditMode = true)]
[Required]
public Decimal ThursdayHours { get; set; }
//[DisplayFormat(DataFormatString = "{0:#.#}", ApplyFormatInEditMode = true)]
[Required]
public Decimal FrydayHours { get; set; }
//[DisplayFormat(DataFormatString = "{0:#.#}", ApplyFormatInEditMode = true)]
[Required]
public Decimal SaterdayHours { get; set; }
//[DisplayFormat(DataFormatString = "{0:#.#}", ApplyFormatInEditMode = true)]
[Required]
public Decimal SundayHOurs { get; set; }
/*
public string TextMonday { get; set; }
public string TextTuesday { get; set; }
public string TextWendsday { get; set; }
public string TextThursday { get; set; }
public string TextFryday { get; set; }
public string TextSaterday { get; set; }
public string TextSunday { get; set; }
*/
public decimal GetTotalHours()
{
return MondayHours +
TuesdayHours +
WendsdayHours +
ThursdayHours +
FrydayHours +
SaterdayHours +
SundayHOurs;
}
//public IEnumerable<SelectListItem> Hour { get; set; }
public Hour()
{
// this.Activity = new List<Activity>();
//Activity = new List<Activity>();
this.yearNumber = DateTime.Now.Year;
Days = DateTime.Now.DayOfWeek - DayOfWeek.Monday;
Monday = DateTime.Now.AddDays(-Days);
Tuesday = DateTime.Now.AddDays(0);// .Monday.AddDays(1).ToShortDateString();//.ToShortDateString());
Wendsday = DateTime.Now.AddDays(1); //DateTime.Parse(Monday.AddDays(2).ToShortDateString());
Thursday = DateTime.Now.AddDays(2); //DateTime.Parse(Monday.AddDays(3).ToShortDateString());
Fryday = DateTime.Now.AddDays(3); //DateTime.Parse(Monday.AddDays(4).ToShortDateString());
Saterday = DateTime.Now.AddDays(4); //DateTime.Parse(Monday.AddDays(5).ToShortDateString());
Sunday = DateTime.Now.AddDays(5); //DateTime.Parse(Monday.AddDays(6).ToShortDateString());
this.WeekNumber = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar.GetWeekOfYear(DateTime.Now, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
}
}
[/code]
Controller:
[code]
public class HourController : Controller
{
private TimeSheetContext db = new TimeSheetContext();
//
// GET: /Hour/
public ActionResult Index()
{
ViewBag.Projects = db.Projects.ToList();
ViewBag.Activities = db.Activities.ToList();
//ViewBag.Hours = db.Hours.ToList();
db.Activities = this.db.Activities;
var Hours = db.Hours.Include(a => a.Activity).Include(a => a.Activity.Project);
return View(db.Hours.ToList());
}//end method Index
/*
[HttpPost]
public ActionResult Index(int year)
{
return new EmptyResult();
}
*/
//
// GET: /Hour/Details/5
public ViewResult Details(int id)
{
Hour hour = db.Hours.Find(id);
return View(hour);
}
//
// GET: /Hour/Create
//Just getting the page from URL.Getting the data(Raw data).
public ActionResult Create()
{
ViewBag.HourID = new SelectList(db.Hours, "HourID", "HourID");
// ViewBag.ActivityID = new SelectList(db.Projects);
// ViewBag.ProjectID = new SelectList(db.Activities);
ViewBag.Projects = db.Projects.ToList();
ViewBag.Activities = db.Activities.ToList();
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)]
//[HttpPost]
public JsonResult GetProjectList(string id)
{
if (id == "")
{
id = "1";
}
int p_id = (int) Convert.ToInt32(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
/*
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult PostProjects(Hour hour)
{
return Json(new {succes = true});
}
*/
//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 IList<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
/*
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ActivitiesByProjects(int ActivityID)
{
var str = (from )
}
*/
[AcceptVerbs(HttpVerbs.Post)]
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(FormCollection formCollection, Hour hour/*, Project project, Activity activity/*, int? selectedProjectID*/)
{
/*
int p_id = Convert.ToInt32(hour.Activity.Project);
int a_id = Convert.ToInt32(hour.Activity);
Activity a = db.Activities.Single(s => s.ActivityID == a_id);
Project p = db.Projects.Single(x => x.ProjectID == p_id);
*/
//hour.Activity.Project = a.Name;
//hour.Activity = activity.Name;
//hour.Activity.Project = activity.Name;
//GetProjects(2);
hour.ActivityID = hour.Activity.ActivityID;
hour.Activity = db.Activities.FirstOrDefault(activity => activity.ActivityID == hour.ActivityID);
//var Activities = selectedProjectID.HasValue;
try
{
if (ModelState.IsValid)
{
if (db.Hours != null)
db.Hours.Add(hour);
if (db.Activities != null) db.Activities.Add(hour.Activity);
//db.Hours.Add(hour.Activity.Project);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException exception)
{
ModelState.AddModelError("", exception);
}//end catch exception.
//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
[/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();
$.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.ProjectID, new SelectList(ViewBag.Projects as IEnumerable,"ProjectID","Name") , new {id ="project"})
@Html.ValidationMessageFor(model=> model.Activity.Project.Name)
</div>
</td>
</tr>
@{
var ActivitySelectList = new SelectList(Enumerable.Empty<SelectListItem>(), "ActivityID", "Name", Model.ActivityID);
}
<tr>
<td>
<div class="editor-label">
@Html.LabelFor(model=> model.Activity.Name)
</div>
</td>
<td>
<div class="editor-field">
@Html.DropDownListFor(model => model.Activity, ActivitySelectList,"Hallo", new {id = "activity"})
@Html.ValidationMessageFor(model=> model.ActivityID)
</div>
</td>
</tr>
</table>
<br/>
[/code]
but I get this error:
Server Error in '/' Application.
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
Source Error: Line 146: Line 147: //GetProjects(2); Line 148: hour.ActivityID = hour.Activity.ActivityID; Line 149: hour.Activity = db.Activities.FirstOrDefault(activity => activity.ActivityID == hour.ActivityID); Line 150: //var Activities = selectedProjectID.HasValue; |
Source File: F:\WinituProjects19-07-2012\winituProjects08-07-2012\ManyToMany26-05-2012WorkingVersionWorkingVersion03 - Copy\ManyToMany\Controllers\HourController.cs
Line: 148
Stack Trace:
THX for helping