albert albert

albert albert

  • NA
  • 524
  • 0

cascading dropdownlist

Jun 15 2012 10:53 AM
Hi everybody,

I have two dropdownList, with: Projects and Activities.

U can select from the first dropdownlist the projects and then u will get the correct activities accosiated with the project.

I have this:

HourController
[code]

  [Authorize(Roles = "Administrator")]
  public class HourController : Controller
  {
  private TimeSheetContext db = new TimeSheetContext();


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

  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());
  var Hours = db.Hours.Include(a => a.Activity).Include(a => a.Activity.Project);
  return View(db.Hours.ToList());
  }
}
[/code]

The view:

[code]


@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(m => m.Activity.ProjectID,ActivityFilter.GetProjects())
  @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(m=> m.Activity, new List<SelectListItem>())
  @Html.ValidationMessageFor(model=> model.ActivityID)
  </div>
  </td>
  </tr>
 
  </table>

[/code]


ActivityFilter:
[code]
public class ActivityFilter
  {
  private static TimeSheetContext timeSheet;

  public static TimeSheetContext TimeSheet
  {
 
  get
  {
  if(timeSheet == null)
  {
  timeSheet = new TimeSheetContext();
  }
  return timeSheet;
  }
  }

  public static  IEnumerable<SelectListItem> GetProjects()
  {
  return timeSheet.Projects.ToList().Select(a => new SelectListItem() {Value = a.ProjectID.ToString(), Text = a.Name});

  }

  public static  IEnumerable<SelectListItem>GetActivities(int? ProductID)
  {
  return timeSheet.Activities.Where(a => !ProductID.HasValue ||
  (ProductID.HasValue &&
  a.Activities.Any(model => model.ActivityID == ProductID))).ToList()
  .Select(m => new SelectListItem() {Value = m.ActivityID.ToString(), Text = m.Name});

  }

  public Project Project { get; set; }
  public Activity Activity { get; set; }
  }
[/code]

JScript:

[code]
function selectFromAjax(url, formData, target) {
  $(target).html("");
  if (formData.id) {
  $.ajax({
  type: 'POST',
  url: url,
  data: formData,
  success: function (data, textStatus) {
  if (data) {
  $(data.items).each(function () {
  $(target).append($("<option></option>").attr("value", this.Value).text(this.Text));
  });
  $(target).change();
  }
  },
  dataType: 'json'
  });
  }
  else {
  $(target).change();
  }
}

[/code]

But I get this error:

[code]

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 26: public static IEnumerable<SelectListItem> GetProjects() Line 27: { Line 28: return timeSheet.Projects.ToList().Select(a => new SelectListItem() {Value = a.ProjectID.ToString(), Text = a.Name}); Line 29: Line 30: }

Source File: F:\WinituProjects07-06-2012\ManyToMany26-05-2012WorkingVersionWorkingVersion02 - Copy\ManyToMany\Models\ActivityFilter.cs   Line: 28

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.] ManyToMany.Models.ActivityFilter.GetProjects() in F:\WinituProjects07-06-2012\ManyToMany26-05-2012WorkingVersionWorkingVersion02 - Copy\ManyToMany\Models\ActivityFilter.cs:28 ASP._Page_Views_Hour_Create_cshtml.Execute() in f:\WinituProjects07-06-2012\ManyToMany26-05-2012WorkingVersionWorkingVersion02 - Copy\ManyToMany\Views\Hour\Create.cshtml:41 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81 System.Web.WebPages.StartPage.RunPage() +19 System.Web.WebPages.StartPage.ExecutePageHierarchy() +65 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76 System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +220 System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +303 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13 System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260 System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343 System.Web.Mvc.Controller.ExecuteCore() +116 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
[/code]



Answers (4)