Search code examples
asp.net-mvcasp.net-corepostviewmodel

handling form in controller using viewmodel with two parameters


I want to save values from a form to my database. I'm using a viewmodel with an selectlist property and a regular model. The value from the dropdown doesn't get saved. Despite being a trivial and seemingly pretty simple thing, I'm pretty lost. Below my code:

Model:

public class Movie
    {
        public int MovieID { get; set; }
        public string Name { get; set; }

        public int StudioID { get; set; }
        public Studio Studio { get; set; }
    }

My ViewModel:

public class CreateMoviesViewModel
    {
        public Movie Movie { get; set; }
        public IEnumerable<SelectListItem> StudiosSelectList { get; set; }
    }

My Controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(CreateMoviesViewModel movieViewModel)
    {
        if (ModelState.IsValid)
        {                
            _context.Add(movieViewModel);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        movieViewModel.StudiosSelectList = new SelectList(_context.Studios.AsNoTracking(), "StudioID", "Name");

        return View(movieViewModel);

And finally, my Form:

      <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Movie.MovieID" />
            <div class="form-group">
                <label asp-for="Movie.Name" class="control-label"></label>
                <input asp-for="Movie.Name" class="form-control" />
                <span asp-validation-for="Movie.Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Movie.StudioID" class="control-label"></label>
                @Html.DropDownListFor(m => m.StudiosSelectList, Model.StudiosSelectList, "Select one")
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>

It is probably something wrong with my dropdown list, or with the logic described in the POST section. Any help is greatly appreciated!


Solution

  • You need to pass the selected dropdown value to your model:

    public class CreateMoviesViewModel
    {
        public int SelectedValueId { get; set; } // <-- not sure what are you selecting, this could be MovieId if you are selecting a movie
        public Movie Movie { get; set; }
        public IEnumerable<SelectListItem> StudiosSelectList { get; set; }
    }
    

    Then you can use:

    @Html.DropDownListFor(m => m.SelectedValueId, m.StudiosSelectList)
    

    This way, the selected value Id would be passed to your model.

    SelectValueId should be initialized to the default value that you want to display in the Dropdown.