ASP.Net MVC视图页面顺序下拉列表不起作用



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

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

更新:增加型号

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

更新:这是控制器:

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

该列表不会填充,在控制台窗口中调试时,它会返回一个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

您可以尝试在ajax调用中添加完整的服务器URL,并在操作方法上添加[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);
}

最新更新