如何摆脱DropDownListFor MVC3 [英] How to get rid of DropDownListFor MVC3

查看:49
本文介绍了如何摆脱DropDownListFor MVC3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Problem: How to get rid of the event drop down?

当我在视图中将其注释掉时,出现模型验证错误.它不知道与哪个事件相关联.即使我在create操作中已将其告知-如所示,因为它已选择了正确的下拉选项.

When I comment it out in the view I get Model validation errors. It doesn't know which Event to associate it with. Even though I'd told it in the create action - as shown because it has selected the correct drop down option.

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

推荐答案

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

If I understand you correctly (and I'm not sure I do), you're confused as to why racesViewModel.RaceInVM.EventU isn't populated on the POST action, even though you set it in the GET action? If so, the answer is that the GET and POST are completely separate actions as far as your server-side local variables are concerned - the only state that is "maintained" across calls is whatever is round-tripped down to the client and up to the server, which only happens when you explicitly put form elements in the view that will cause that data to be included in the HTML and posted back up to the server. The solution is to either replace the Html.DropDownFor with an Html.HiddenFor, or else just repopulate the variable in the POST action (in which case I'm not sure you'd need to populate it in the GET action at all.)

这篇关于如何摆脱DropDownListFor MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆