How to get rid of DropDownListFor MVC3

2019-08-31 23:59发布

问题:

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

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

view

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

post:

 [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:

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.)