【问题标题】:Cascading dropdownlist with mvc and jQuery not working使用 mvc 和 jQuery 级联下拉列表不起作用
【发布时间】:2010-12-06 21:07:16
【问题描述】:

我正在尝试使用一种用于级联下拉列表的解决方案(一个下拉列表中的选择决定了第二个下拉列表中的选项):

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>

这是获取任务的 Action 方法:

    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 表达式由于某种原因似乎不起作用,这真的很奇怪,因为我以前一直在使用这种表达式,没有任何问题。也许我累了,错过了什么,但我看不到它。该表达式返回所有任务,而不仅仅是与当前客户具有相同 ID 的任务。 foreach 工作正常,这使得它更加奇怪......这与第一个问题完全无关,因为再次,foreach 工作正常并且只选择三个任务(这是正确的)。但是第二个下拉列表仍然显示所有任务...

任何帮助表示赞赏!

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>

更新:

我现在将其更新为以下内容:

获取与所选客户关联的任务的操作方法:

    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();
    });

但我想知道如何获取下拉列表的默认值。因为否则,当您第一次访问该页面时,客户下拉列表将具有值,但任务列表不会...

【问题讨论】:

  • 你确定action方法是完整的吗? _model.Tasks 来自哪里?使用它的代码已被注释掉 - 因此该行无法编译,或者您是否取消了注释?请完整发布操作方法。
  • 不,就像我提到的那样,我注释掉了 linq 表达式,因为它不起作用。 foreach 与 linq 应该做的事情相同。 _model.Tasks 是包含数据库数据的模型。我没有包含获取数据的代码。但是这种操作方法有效。这只是不起作用的 linq 表达式(因此被注释掉)。但我仍然想知道为什么 linq 表达式不起作用(当然,当未注释时)。但主要是,我想知道为什么 jQuery 似乎没有用结果任务填充第二个下拉列表...

标签: asp.net linq asp.net-mvc-2 drop-down-menu


【解决方案1】:

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 });

【讨论】:

  • 嗯,好的...但是我不确定我知道如何处理该帖子,这有点超出我的想象。我正在为我的模型使用实体框架,我想我不应该在那里引入任何属性([ScriptIgnore]),因为如果我更新模型,它就会消失。我确实有一个 ViewModel 来简化对模型的访问。但这只是有一堆属性访问客户、任务等的集合。我不知道在哪里使用这个属性......
  • 谢谢,是的,我认为跳过循环解决方法会更好,我尝试了您的建议。它确实改变了一些似乎在正确轨道上的东西,但我现在在任务下拉列表中得到“未定义”作为值。请参阅上面的更新。我做错了什么?
  • 我用你建议的代码让它工作了。您能否告诉我如何在第一个下拉列表中获取默认值?
  • 想通了。只需在 selectlist 参数之后添加它: m.Customers, new SelectList(Model.Customers, "Id", "Name"), "Please select...", new { @id = "CustomerId" })%> 感谢 CGK 的所有帮助!
猜你喜欢
  • 1970-01-01
  • 2018-04-12
  • 2016-12-15
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 2011-10-05
  • 1970-01-01
相关资源
最近更新 更多