Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ASP.Net MVC查看页面顺序下拉列表不工作_Javascript_C#_Asp.net Mvc - Fatal编程技术网

Javascript ASP.Net MVC查看页面顺序下拉列表不工作

Javascript ASP.Net MVC查看页面顺序下拉列表不工作,javascript,c#,asp.net-mvc,Javascript,C#,Asp.net Mvc,我正在将代码从一个项目转移到另一个项目。虽然这段代码在另一个项目中似乎有效,但在新项目中却不起作用。我不确定我是否遗漏了什么 我有3个下拉列表,它们依赖于最后一个下拉列表来填充。国家、州和城市。而这个国家是独立的 更新:添加模型 public IEnumerable<SelectListItem> Countries { get; set; } public IEnumerable<SelectListItem> States { get; set; }

我正在将代码从一个项目转移到另一个项目。虽然这段代码在另一个项目中似乎有效,但在新项目中却不起作用。我不确定我是否遗漏了什么

我有3个下拉列表,它们依赖于最后一个下拉列表来填充。国家、州和城市。而这个国家是独立的

更新:添加模型

    public IEnumerable<SelectListItem> Countries { get; set; }
    public IEnumerable<SelectListItem> States { get; set; }
    public IEnumerable<SelectListItem> Cities { get; set; }
更新: 看起来我现在没有收到任何错误,但在选择国家后仍然没有填充州列表。。我的问题是理解为什么原来的解决方案在另一个解决方案中有效,而不是在这个解决方案中

更新:将此移至新问题。这似乎是一个脚本冲突! 可在此处找到这一点的延续:

您可以尝试在ajax调用中添加完整的服务器URL,并在action方法中添加[HttpPost]add吗

[HttpPost]
       public JsonResult Add(string countryId)
        {
            int Id;
            Id = Convert.ToInt32(countryId);

            var states = from a in db.States where a.CountryId == Id select a;
            return Json(states, JsonRequestBehavior.AllowGet);

        }

您能否使用浏览器的开发工具共享通过网络传输的内容?这是一个猜测,但是如果
countryId
为空/null,那么
Convert.ToInt32
可能会爆炸。如果您在控制器操作
Add
中设置了一个断点,它会命中吗?是的,我会得到id。但是当它在返回Json时通过一个断点时,States会出现一个错误,说“函数求值需要所有线程运行”,在这一点上,我认为它会有状态。控制台有这个。jquery-3.4.1.js:9837 POST 500(内部服务器错误)。Javascript有以下命令-try{//Do发送请求(这可能引发异常)xhr.send(options.hasContent&&options.data | | null);这两个项目之间的唯一区别是,我在本项目中使用了3.4.1,而在原始项目中使用了3.3.1。不确定我是否遗漏了任何其他内容。同时,在服务器端,它正在执行查询并获取数据运行探查器。您可以发布堆栈跟踪吗?错误代码500可能是任何内容。此时,将HttpPost添加到本项目中如果不抛出错误,则不会填充任何列表。。
<script type="text/javascript">
$(function () {
    $('#ddlCountry').change(function () {
        //debugger;
        $.ajax({
            type: "post",
            url: "/States/Add",
            data: { countryId: $('#ddlCountry').val() },
            datatype: "json",
            traditional: true,
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#ddlState').append('<option value="' + value.StateId + '">' + value.StateName + '</option>');
                });
            }
        });
    });

    $('#ddlState').change(function () {
        $.ajax({
            type: "post",
            url: "/Cities/Add",
            data: { stateId: $('#ddlState').val() },
            datatype: "json",
            traditional: true,
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#ddlCity').append('<option value="' + value.CityId + '">' + value.CityName + '</option>');
                });
            }
        });
    });
});
public ActionResult Create()
    {
        try
        {
            GeneralEntities generalEntities = new GeneralEntities();
            List<SelectListItem> countryNames = new List<SelectListItem>();
            VendorViewModel casModel = new VendorViewModel();

            List<Countries> countries = generalEntities.Countries.ToList();
            countries.ForEach(x =>
            {
                countryNames.Add(new SelectListItem { Text = x.CountryName, Value = x.CountryId.ToString() });
            });
            casModel.Countries = countryNames;

            return View(casModel);
        }
        catch (Exception)
        {

            return View();
        }
    }
    //Get States --- Resides in the StatesController
    public JsonResult Add(string countryId)
    {
        int Id;
        Id = Convert.ToInt32(countryId);

        var states = from a in db.States where a.CountryId == Id select a;
        return Json(states, JsonRequestBehavior.AllowGet);

    }
There is already an open DataReader associated with this Command which must be closed first.
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.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.

Source Error:

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.

Stack Trace:


[InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]

System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command) +1642350
   System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command) +91
   System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +274
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +119
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +65
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +170
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +43
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
   System.Data.Entity.Infrastructure.Interception.<>c.<Reader>b__6_0(DbCommand t, DbCommandInterceptionContext`1 c) +15
   System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
   System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +438
   System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +166
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
   System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +37

[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
   System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +112
   System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +745
   System.Data.Entity.Core.Objects.<>c__DisplayClass41_0.<GetResults>b__1() +97
   System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +292
   System.Data.Entity.Core.Objects.<>c__DisplayClass41_0.<GetResults>b__0() +179
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +189
   System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +281
   System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption) +31
   System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption) +138
   System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad() +342
   System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty(TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject) +86
   System.Data.Entity.Core.Objects.Internal.<>c__DisplayClass0_0`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item) +102
   System.Data.Entity.DynamicProxies.States_099B6D7821CA994DC43D6B921B123F55DDD45CBE606FA44560F0517091322265.get_Countries2() +32

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +91
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +105
   System.Web.SecurityUtils.MethodInfoInvoke(MethodInfo method, Object target, Object[] args) +168
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +461
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +1324
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +195
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +127
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +1279
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +195
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat) +29
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat) +64
   System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +343
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
   System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +198
   System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
   System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9836613
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
MultipleActiveResultSets=True
[HttpPost]
       public JsonResult Add(string countryId)
        {
            int Id;
            Id = Convert.ToInt32(countryId);

            var states = from a in db.States where a.CountryId == Id select a;
            return Json(states, JsonRequestBehavior.AllowGet);

        }