【问题标题】:handling form in controller using viewmodel with two parameters使用带有两个参数的视图模型在控制器中处理表单
【发布时间】:2019-08-29 20:09:20
【问题描述】:

我想将表单中的值保存到我的数据库中。我正在使用具有选择列表属性和常规模型的视图模型。下拉列表中的值不会被保存。尽管这是一件微不足道且看似非常简单的事情,但我还是很迷茫。 在我的代码下面:

型号:

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

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

我的视图模型:

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

我的控制器:

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

最后,我的表单:

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

这可能是我的下拉列表或 POST 部分中描述的逻辑有问题。非常感谢任何帮助!

【问题讨论】:

    标签: asp.net-mvc asp.net-core post viewmodel


    【解决方案1】:

    您需要将选定的下拉值传递给您的模型:

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

    那么你可以使用:

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

    这样,选定的值 Id 将被传递给您的模型。

    SelectValueId 应初始化为您希望在下拉菜单中显示的默认值。

    【讨论】:

      猜你喜欢
      • 2011-11-21
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多