下拉列表不断告诉我有没有重复

时间:2018-03-23 18:44:14

标签: c# asp.net-mvc razor drop-down-menu

目标是在主要下拉列表的项目发生更改时更改辅助下拉列表的项目。

凭借极其自信和乐观的想法,我提出了这个简单的代码:

型号:

public class ChoixModel
{
    public INSC_Inscription inscription { get; set; }
    public List<Ecole> ecoles { get; set; }
    public List<Programme> programmes { get; set; }
    public int? ecoleChoi1 { get; set; }
    public int? programmeChoi1 { get; set; }
}

控制器:

    public ActionResult Phase1(int idInscrip)
    {
        inscriptionPrimaireEntities db = new inscriptionPrimaireEntities();
        ChoixModel model = new ChoixModel();

        if (model.ecoleChoi1 == null)
            model.ecoleChoi1 = db.Ecole.FirstOrDefault()?.id;

        model.ecoles = db.Ecole.ToList();
        model.programmes = db.Programme.Where(t => t.FK_Ecole == model.ecoleChoi1).ToList();

        return View(model);
    }

    [HttpPost]
    public ActionResult Phase1(ChoixModel model, string submiter)
    {
        inscriptionPrimaireEntities db = new inscriptionPrimaireEntities();

        if (!string.IsNullOrWhiteSpace(submiter))
        {
            if (model.ecoleChoi1 != null)
                model.programmeChoi1 = db.Programme.FirstOrDefault(t => t.id == model.inscription.Programme1)?.id;
        }

        return View(model);
    }

查看:

@using System.Web.UI.WebControls
@using inscriptionPrimaire.Models
@model ChoixModel
@{
    ViewBag.Title = "Phase1";
    Layout = "~/Views/Shared/_Layout.cshtml";

    SelectList selectEcole = new SelectList(Model.ecoles, "id", "NomAffiche");
    SelectList selectPrograme = new SelectList(Model.programmes, "id","NomAffiche");
}

<form method="post" action="@Url.Action("Phase1", "Choix")" id="ViewModelForm">

<br /><br />

<table>
    <tr>
        <td style="min-width: 152px;"> 

        @Html.DropDownListFor(t => t.ecoleChoi1, selectEcole, new { @class = "form-control", style = "min-width: 150px;", onchange = "this.form.submit();" })

        </td>
        <td style="min-width: 152px;">

        @Html.DropDownListFor(t => t.programmeChoi1, selectPrograme, new { @class = "form-control", style = "min-width: 150px;" })

        </td>
    </tr>
</table>

</form>

单击以更改主下拉列表Ecole中的选定项目时,会发生错误。我怀疑这与我如何使用提交有关:

@Html.DropDownListFor(t => t.ecoleChoi1, selectEcole, new { @class = "form-control", style = "min-width: 150px;", onchange = "this.form.submit();" })

预期的行为是,当我更改选定的下拉列表Ecole时,它会将下拉列表Programme填入所选Ecole所提供的实际程序。

相反,我有一个错误,一个调试甚至无法捕获的错误,它只在浏览器中显示:

  

已添加具有相同键的项目

所以我去查看我的数据库中是否有任何重复...两个表中甚至没有一行包含与前一个相同的任何内容。

我被要求显示完整的堆栈跟踪(用法语表示):

Erreur du serveur dans l'application '/'.
Un élément avec la même clé a déjà été ajouté.
Description : Une exception non gérée s'est produite au moment de l'exécution de la requête Web actuelle. Contrôlez la trace de la pile pour plus d'informations sur l'erreur et son origine dans le code. 

Détails de l'exception: System.ArgumentException: Un élément avec la même clé a déjà été ajouté.

Erreur source: 

Une exception non gérée s'est produite lors de l'exécution de la requête Web actuelle. Les informations relatives à l'origine et l'emplacement de l'exception peuvent être identifiées en utilisant la trace de la pile d'exception ci-dessous.

Trace de la pile: 


[ArgumentException: Un élément avec la même clé a déjà été ajouté.]
   System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52
   System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +12534430
   System.Collections.Generic.CollectionExtensions.ToDictionaryFast(TValue[] array, Func`2 keySelector, IEqualityComparer`1 comparer) +116
   System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +136
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +176
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +101
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +55
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1197
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +330
   System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +17
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +377
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +101
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +55
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1197
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +330
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +331
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +743
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +343
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +465
   System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

HTML OUTPUT: Ecole

Programme

1 个答案:

答案 0 :(得分:3)

问题是您正在使用复杂的数据库实体模型,模型绑定器无法从表单数据中正确地重建。

我建议您避免使用往返实体并仅接受所需的值。您可以通过从HttpPost方法中删除模型并直接接受值来完成此操作:

 [HttpPost]
 public ActionResult Phase1(int ecoleChoi1 , int programmeChoi1, string submiter)
 { 
      //... 
      //You can then reconstruct the model if necessary and send back
      ChoixModel model = new ChoixModel();
      //...
      return View(model);
 }

在Razor视图中:

 @Html.DropDownList("ecoleChoi1 ", selectEcole, new { @class = "form-control", style = "min-width: 150px;", onchange = "this.form.submit();" })

 @Html.DropDownList("programmeChoi1", selectPrograme, new { @class = "form-control", style = "min-width: 150px;" })

如果你调试它,你会发现模型绑定器传回了下拉列表中的值。

或者,由于这两个列表不是真正可编辑的字段而是选择字段,因此您可以将它们从模型中删除并在ViewBag中传递它们。这样你就可以继续接受你的模型了。