ASP.NET 核心 MVC 视图模型属性在发布时返回空值



在视图模型类中我有一个属性

public List<SelectListItem> Genres { get; set; }

从数据库中获取。但是,当提交表单时,此属性是 零。

这是Get行动

[HttpGet]
[Route("PostAd")]
public async Task<IActionResult> PostAd()
{
var model = new PostAdViewModel();
var Genres = new List<SelectListItem>();
var dbGenres = _appDbContext.Genres.ToList();
var SelectListGroups = dbGenres.Where(x => x.ParentId == 0)
.ToDictionary(y => y.Id,y=>new SelectListGroup(){Name = y.Name});
foreach (var genre in dbGenres)
{
if (genre.ParentId != 0)
{
Genres.Add(new SelectListItem()
{
Value = genre.Id.ToString(),
Text = genre.Name,
Group = SelectListGroups[genre.ParentId]
});
}
}
model.Genres = Genres;
return View(model);
}

这是发布方法

[HttpPost]
[Route("PostAd")]
public async Task<IActionResult> PostAd(PostAdViewModel model)
{
if (ModelState.IsValid)
{
return null;
}
else
{
return View(model);
}
}

这是视图

<form class="form-horizontal" asp-controller="Ads" asp-action="PostAd" enctype="multipart/form-data">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group row">
<label  class="col-sm-3 col-form-label">Janr</label>
<div class="col-sm-8">
@* @Html.DropDownListFor(model => Model.Genres, Model.Genres, "Janr", new { @class = "form-control",@id = "lstGenres", @multiple = "multiple", @title= "Janr Seçin" }) *@
@Html.DropDownListFor(model =>  model.SelectedGenres,Model.Genres,new { @class = "form-control",@id = "lstGenres", @multiple = "multiple", @title= "Janr Seçin",@name = "SelectGenre" })
</div>
</div>
<div class="form-group row">
<label for="" class="col-sm-3 col-form-label">Add Type</label>

<div class="col-sm-8"><button type="submit" id="button1id"
class="btn btn-success btn-lg" asp-action="PostAd" asp-controller="Ads">Submit</button></div>
</div>
</form>

所以每次提交此表单时,"流派"集合都会返回 null,我该如何解决这个问题? 谢谢

该属性也需要在Post上重新填充

创建一个通用函数来获取数据

private List<SelectListItem> getGenres () {
var Genres = new List<SelectListItem>();
var dbGenres = _appDbContext.Genres.ToList();
var SelectListGroups = dbGenres.Where(x => x.ParentId == 0)
.ToDictionary(y => y.Id,y=> new SelectListGroup(){ Name = y.Name });
foreach (var genre in dbGenres) {
if (genre.ParentId != 0) {
Genres.Add(new SelectListItem() {
Value = genre.Id.ToString(),
Text = genre.Name,
Group = SelectListGroups[genre.ParentId]
});
}
}
return Genres;
}

并在控制器操作中调用它。

[HttpGet]
[Route("PostAd")]
public IActionResult PostAd() {
var model = new PostAdViewModel();           
model.Genres = getGenres();
return View(model);
}
[HttpPost]
[Route("PostAd")]
public IActionResult PostAd(PostAdViewModel model) {
if (ModelState.IsValid) {
//...do something with model
//and redirect if needed
}
//if we reach this far model is invalid
//and needs to be repopulated
model.Genres = getGenres();
return View(model);
}

最新更新