Я нахожусь в процессе передачи кода из одного проекта в другой. Хотя этот код, кажется, работает в другом проекте, он не работает в новом. Я не уверен, что я что-то упустил или нет.
У меня есть 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>
ОБНОВЛЕНО: My 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