前端需要录入用户账号,但客户要求最好是选择式的,并且只是显示用户名就好。
但前端已经做好,采用双模型的viewmodel来做太麻烦,就采用了下述方法。
后端代码:
List<SelectListItem> li = new List<SelectListItem>(); var us = _context.assetUsers; foreach (var item in us) { SelectListItem listItem = new SelectListItem(); listItem.Text = item.Name; listItem.Value = item.OwnerID.ToString(); li.Add(listItem); } ViewBag.AllUser = li;
前端引入:
<select asp-for="AsOwner" class="form-control"> <option hidden></option> @foreach (var item in (List<SelectListItem>)ViewBag.AllUser) { <option value=@item.Value> @item.Text</option>@*value存储的是账号,text为用户名*@ } </select>
利用ViewBag引入Model
var al = _context.asUsers.ToList();
ViewBag.User = al;
前端引入ViewBag.User并将其转为list<model>
@{ ViewData["Title"] = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; var Uname = ViewBag.User as List<as.Models.AssetUser>; }
前端显示
<td> @*@Html.DisplayFor(modelItem => item.AssetOwner)*@ @*@item.AssetOwner*@ @if (Uname.Where(n => n.OwnerID.Equals(item.AssetOwner)) == null) { @item.AssetOwner } else { @Uname.Where(n => n.OwnerID.Equals(item.AssetOwner)).FirstOrDefault().Name } </td>