簡體   English   中英

ASP.Net MVC 查看頁面順序下拉列表不起作用

[英]ASP.Net MVC View Page Sequential drop down lists not working

我正在將代碼從一個項目轉移到另一個項目。 雖然此代碼似乎適用於其他項目,但不適用於新項目。 我不確定我是否遺漏了什么。

我有 3 個下拉列表,它們依賴於最后一個下拉列表來填充。 國家、State 和城市。 雖然國家是獨立的。

更新:添加了 Model

    public IEnumerable<SelectListItem> Countries { get; set; }
    public IEnumerable<SelectListItem> States { get; set; }
    public IEnumerable<SelectListItem> Cities { get; set; }

更新:這是下拉代碼。

<div class="form-group">
   @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label" })
   @Html.DropDownListFor(model => Model.Country, Model.Countries, "---Select Country---", new { @class = "", @id = "ddlCountry" })
   @Html.ValidationMessageFor(model => model.Country, "", new { @class = "text-danger" })
 </div>

 <div class="form-group">
   @Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label" })
   @Html.DropDownListFor(model => model.State, new List<SelectListItem>(), "---Select State---", new { @class = "", @id = "ddlState" })
   @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
 </div>

 <div class="form-group">
   @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label" })
   @Html.DropDownListFor(model => model.City, new List<SelectListItem>(), "---Select City---", new { @class = "", @id = "ddlCity" })
   @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
 </div>

更新:我的 Javascript:

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

更新:這是 controller:

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

    }

該列表未填充,並且在控制台 window 中調試時返回 500 服務器錯誤。 我有沒有設置正確的權限? 或者我的代碼中缺少什么?

謝謝你的幫助..

更新:堆棧跟蹤..

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

更新:看來我現在沒有收到任何錯誤,但在選擇國家后仍然沒有填充國家列表。我遇到的問題是理解為什么原來的解決方案在另一個解決方案中工作而不是在這個解決方案中......

更新:將此移至一個新問題。 它似乎是一個腳本沖突:可以在這里找到它的延續: stackoverflow.com/questions/60386156

您可以嘗試將完整服務器 URL 添加到 ajax 調用並在操作方法上添加 [HttpPost]

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

        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM