2010-12-06 198 views
0

我試圖使用級聯下拉列表的解決方案級聯下拉列表(在一個下拉列表中選擇確定的第二個選項),在這裏找到:與MVC和jQuery不工作

http://www.pieterg.com/post/2010/04/12/Cascading-DropDownList-with-ASPNET-MVC-and-JQuery.aspx

<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script> 
    <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      //Hook onto the MakeID list's onchange event 
      $("#CustomerId").change(function() { 
       //build the request url 
       var url = "Timesheet/Tasks"; 
       //fire off the request, passing it the id which is the MakeID's selected item value 
       $.getJSON(url, { id: $("#CustomerId").val() }, function (data) { 
        //Clear the Model list 
        $("#TaskId").empty(); 
        //Foreach Model in the list, add a model option from the data returned 
        $.each(data, function (index, optionData) { 
         $("#TaskId").append("<option value='" + optionData.ID + "'>" + optionData.Description + "</option>"); 
        }); 
       }); 
      }).change(); 
     }); 
    </script> 
    <h2> 
     Index</h2> 
    <fieldset> 
     <legend>Fields</legend> 
     <div> 
      <label for="Customers"> 
       Kund:</label> 
      <%:Html.DropDownListFor(m => m.Customers, new SelectList(Model.Customers,"Id", "Name"), new {@id="CustomerId"}) %> 
      <%--<%:Html.DropDownListFor(m => m.CustomerId, new SelectList(Model.Customers,"Id", "Name")) %>--%> 
      &nbsp;&nbsp; 
      <label for="Tasks"> 
       Aktiviteter:</label> 
      <%:Html.DropDownListFor(m => m.Tasks, new SelectList(Model.Tasks,"Id", "Name"), new {@id="TaskId"}) %> 
      <%--<%:Html.DropDownListFor(m => m.TaskId, new SelectList(Model.Tasks,"Id", "Name")) %>--%> 
<%--   <select id="TaskId" name="TaskId"> 
      </select>--%> 
     </div> 
    </fieldset> 

及這裏的獲取任務的操作方法:

public JsonResult Tasks(string id) 
    { 
     var result = new JsonResult(); 
     //var tasks = from t in _model.Tasks 
     //   where t.CustomerId.ToString() == id 
     //   select t; 
     List<Task> tasklist = new List<Task>(); 
     foreach (var task in _model.Tasks) 
     { 
      if(task.CustomerId.ToString() == id) 
       tasklist.Add(task); 
     } 

     //result.Data = tasks.ToList(); 
     result.Data = tasklist; 

     result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; 
     return result; 
    } 

我有兩個問題:

  1. 第二個下拉列表完全不會改變,這取決於第一個下拉列表。我嘗試了各種變體(正如您從註釋掉的下拉列表中看到的那樣)。我在Firebug中收到錯誤消息,但我無法解釋它(請參閱下文)。
  2. Action方法中的linq表達式由於某種原因似乎不起作用,這真的很奇怪,因爲我之前一直在使用這種表達式而沒有任何問題。也許我很累,想念一些東西,但我看不到它。表達式返回所有任務,而不僅僅是與當前客戶具有相同標識的任務。該foreach工作正常,這使得它更奇怪......這是完全無關的第一個問題,因爲再次,foreach工作正常,只選擇三個任務(這是正確的)。但仍然第二dropdownlist顯示所有任務...

任何幫助讚賞!

Firebug的錯誤日誌:

<html> 
    <head> 
     <title>A circular reference was detected while serializing an object of type 'Tidrapportering.Models.Task'.</title> 
     <style> 
     body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
     p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} 
     b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} 
     H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } 
     H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } 
     pre {font-family:"Lucida Console";font-size: .9em} 
     .marker {font-weight: bold; color: black;text-decoration: none;} 
     .version {color: gray;} 
     .error {margin-bottom: 10px;} 
     .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } 
     </style> 
    </head> 

    <body bgcolor="white"> 

      <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1> 

      <h2> <i>A circular reference was detected while serializing an object of type 'Tidrapportering.Models.Task'.</i> </h2></span> 

      <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif "> 

      <b> Description: </b>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. 

      <br><br> 

      <b> Exception Details: </b>System.InvalidOperationException: A circular reference was detected while serializing an object of type 'Tidrapportering.Models.Task'.<br><br> 

      <b>Source Error:</b> <br><br> 

      <table width=100% bgcolor="#ffffcc"> 
       <tr> 
        <td> 
         <code> 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code> 

        </td> 
       </tr> 
      </table> 

      <br> 

      <b>Stack Trace:</b> <br><br> 

      <table width=100% bgcolor="#ffffcc"> 
       <tr> 
        <td> 
         <code><pre> 

[InvalidOperationException: A circular reference was detected while serializing an object of type &#39;Tidrapportering.Models.Task&#39;.] 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1478 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +126 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1311 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +502 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1355 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +502 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1355 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +126 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1311 
    System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194 
    System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat) +26 
    System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat) +74 
    System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj) +6 
    System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +458 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39 
    System.Web.Mvc.&lt;&gt;c__DisplayClass14.&lt;InvokeActionResultWithFilters&gt;b__11() +60 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +391 
    System.Web.Mvc.&lt;&gt;c__DisplayClass16.&lt;InvokeActionResultWithFilters&gt;b__13() +61 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +285 
    System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830 
    System.Web.Mvc.Controller.ExecuteCore() +136 
    System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111 
    System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39 
    System.Web.Mvc.&lt;&gt;c__DisplayClass8.&lt;BeginProcessRequest&gt;b__4() +65 
    System.Web.Mvc.Async.&lt;&gt;c__DisplayClass1.&lt;MakeVoidDelegate&gt;b__0() +44 
    System.Web.Mvc.Async.&lt;&gt;c__DisplayClass8`1.&lt;BeginSynchronous&gt;b__7(IAsyncResult _) +42 

    System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141 
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54 
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 
    System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52 
    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38 
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105 

    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +184 
</pre></code> 

        </td> 
       </tr> 
      </table> 

      <br> 

      <hr width=100% size=1 color=silver> 

      <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1 

      </font> 

    </body> 
</html> 

UPDATE:

我現在更新到以下幾點:

操作方法與選定的客戶相關聯越來越任務:

public JsonResult Tasks(string id) 
    { 
     var result = new JsonResult(); 
     var tasks = 
      _model.Tasks.Where(task => task.CustomerId.ToString() == id).Select(
       task => new {ID = task.Id, Name = task.Name}); 
     result.Data = tasks; 

     result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; 
     return result; 
    } 

而在視圖中:

<div> 
     <label for="Customers"> 
      Kund:</label> 
     <%:Html.DropDownListFor(m => m.Customers, new SelectList(Model.Customers,"Id", "Name"), new {@id="CustomerId"}) %> 
     &nbsp;&nbsp; 
     <label for="Tasks"> 
      Aktiviteter:</label> 
     <%:Html.DropDownListFor(m => m.Tasks, new SelectList(Model.Tasks,"Id", "Name"), new {@id="TaskId"}) %> 
    </div> 

現在我得到的結果在第二個下拉列表中以某種方式篩選和選擇,選擇不同客戶時的選項數量正確。然而,在任務下拉列表值是爲所有的人「不確定」 ......

更新2:

我發現這個問題:

在jQuery的我忘了固定的屬性名稱的任務對象。這裏的工作版本:

$(document).ready(function() { 
     //Hook onto the MakeID list's onchange event 
     $("#CustomerId").change(function() { 
      //build the request url 
      var url = "Timesheet/Tasks"; 
      //fire off the request, passing it the id which is the MakeID's selected item value 
      $.getJSON(url, { id: $("#CustomerId").val() }, function (data) { 
       //Clear the Model list 
       $("#TaskId").empty(); 
       //Foreach Model in the list, add a model option from the data returned 
       $.each(data, function (index, optionData) { 
        $("#TaskId").append("<option value='" + optionData.Id + "'>" + optionData.Name + "</option>"); 
       }); 
      }); 
     }).change(); 
    }); 

但我想知道如何獲得下拉列表的默認值。因爲否則客戶下拉列表將有一個價值,當你第一次到達頁面,但任務列表將不會...

+0

你確定操作方法是完整的嗎? `_model.Tasks`從哪裏來?使用它的代碼已被註釋掉 - 因此該行不會被編譯,或者您是否將其註釋掉?請完整地發佈操作方法。 – RPM1984 2010-12-06 21:14:12

+0

不,就像我剛纔提到的那樣,我評論了linq表達式,因爲它不起作用。 foreach和linq應該做的一樣。 _model.Tasks是來自數據庫的數據模型。我沒有包含獲取數據的代碼。但是這個行動方法起作用。這只是linq表達式不起作用(因此被註釋掉)。但我仍然想知道爲什麼linq表達式不起作用(當然沒有註釋)。但主要是,我想知道爲什麼jQuery似乎沒有填補結果任務的第二個下拉列表... – Anders 2010-12-06 21:38:35

回答

2

JsonResult使用JavascriptSerializer生成JSON數據,並且JavascriptSerializer不支持循環引用。 也許下面的文章將幫助您解決問題:Json and Circular Reference Exception

更新

而不是周圍的循環引用的工作,只是返回另一個對象的名單,只需要兩個字段:ID和描述。它看起來像這樣:

var tasklist = _model.Tasks.Where(x => x.CustomerId.ToString() == id) 
          .Select(x => new { ID = task.ID, Description = task.Description });