如何摆脱DropDownListFor MVC3

时间:2011-04-29 00:20:58

标签: asp.net-mvc-3

问题:如何摆脱事件下拉?

当我在视图中对其进行评论时,我得到模型验证错误。它不知道将它与哪个事件相关联。即使我在创建操作中告诉它 - 如图所示,因为它已选择了正确的下拉选项。

enter image description here

 public ActionResult Create(Guid idEvent)
    {
        ViewBag.EventName = uow.Events.Single(e => e.Id == idEvent).Name;

        RaceViewModel racesViewModel = new RaceViewModel();
        SetupDropDownsStronglyTyped(racesViewModel);

        Race race = new Race();
        racesViewModel.RaceInVM = race;

        Event _event = uow.Events.Single(e => e.Id == idEvent);
        racesViewModel.RaceInVM.EventU = _event;

        return View(racesViewModel);
    }

视图

<div class="editor-field">
@Html.DropDownListFor(x => x.RaceInVM.EventUId, new SelectList(Model.ListOfEvents, "Id", "Name"))

后:

 [HttpPost]
    public ActionResult Create(RaceViewModel raceViewModel, Guid idEvent)
    {
        if (!ModelState.IsValid)
        {
            SetupDropDownsStronglyTyped(raceViewModel);
            return View(raceViewModel);
        }

        uow.Add(raceViewModel.RaceInVM);
        uow.SaveChanges();
        return RedirectToAction("Index");
    }

1 个答案:

答案 0 :(得分:0)

如果我理解正确(并且我不确定),你会对为什么没有在POST操作中填充racesViewModel.RaceInVM.EventU感到困惑,即使你在GET操作中设置了它?如果是这样,答案是就服务器端本地变量而言,GET和POST是完全独立的操作 - 跨越调用“维持”的唯一状态是向客户端往返的任何状态,直到服务器,只有当您在视图中显式放置表单元素时才会发生这种情况,这会导致数据包含在HTML中并发布回服务器。解决方案是使用Html.HiddenFor替换Html.DropDownFor,或者只是在POST操作中重新填充变量(在这种情况下,我不确定您是否需要在GET操作中填充它。)