我有一個 Index.cshtml 視圖,我使用一個模型來創建一個下拉串列。但我想在 Layout.cshtml 中使用相同的模型并做同樣的事情,但我收到了這個錯誤,我想知道我能做些什么來修復它。我的想法是從布局視圖的索引中重用相同的視圖模型。
索引.cshtml
@model IEnumerable <SelectListItem>
<select id="subSectionID"
@foreach (var item in Model)
{
<option value="@item.Value">@item.Text</option>
}
</select>
布局.cshtml
@model IEnumerable <SelectListItem>
<select id="subSectionID"
@foreach (var item in Model)
{
<option value="@item.Value">@item.Text</option>
}
</select>
控制器
public async Task<ActionResult> Index()
{
var subSections = await UtilityResource.GetSubSections();
var subSectionList = subSections.Select(c => new SelectListItem()
{
Text = c.Name,
Value = c.Id.ToString()
}).ToList();
subSectionList = subSectionList.OrderBy(c => c.Text).ToList();
return View(subSectionList);
}
視圖模型
public class ViewModel
{
public int SelectedSubSectionId { get; set; }
public IEnumerable<SelectListItem> SubSections { get; set; }
public List<VisitVM> VisitVMList { get; set; }
public string SubSectionName { get; set; }
}
}
錯誤:
傳遞到字典中的模型項的型別為“ViewModel”,但此字典需要型別為“System.Collections.Generic.IEnumerable`1[System.Web.Mvc.SelectListItem]”的模型項。
uj5u.com熱心網友回復:
修復動作
var viewModel= new ViewModel{ SubSections = subSectionList};
return View(viewModel);
布局和索引視圖應該有這個代碼
@model ViewModel
....
<select class="form-control" id="subSectionID"
asp-for="@Model.SelectedSubSectionId" asp-items="@Model.SubSections">
<option value="0" >Select</option>
</select>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/490422.html
標籤:C# html asp.net-mvc
