我试图从我的数据库检索数据到一个HTML,而不是检索到Html.DropDownListFor,但我无法检索标记。
NewCustomerViewModel
public class NewCustomerViewModel
{
public int CustId { get; set; }
[Required]
public string CustFirstName { get; set; }
[Required]
public string CustLastName { get; set; }
[Required]
public int StId { get; set; }
public IEnumerable<State> States { get; set; }
}CustomerController
public class CustomerController : Controller
{
private CustomerDbContext _context;
public CustomerController(CustomerDbContext context)
{
_context = context;
}
// GET: /<controller>/
public IActionResult Index()
{
return View(_context.Customers.ToList());
}
public IActionResult Create()
{
var stateNames = _context.States.ToList();
var viewModel = new NewCustomerViewModel
{
States = stateNames
};
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Customer customer)
{
if (ModelState.IsValid)
{
_context.Customers.Add(customer);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
}创建视图
下面的HTML DropDownListFor运行得很好:
@Html.DropDownListFor(m => m.StId, new SelectList(Model.States, "StId", "StName"))不过,我无法让select标记工作。
<select asp-for="StId" asp-items="@Model.States" class="form-control">
<option>Select State</option>
</select>我所有的HTML在我的Create视图中使用,而不是HTML助手,这正是我想要避免的。我只希望能够将数据检索到标记中。
发布于 2016-08-30 20:09:32
对于select标记助手,asp-items需要SelectListItem集合\SelectList,其中的每个项都具有Value和Text属性。Value属性值将用于该选项的值,Text属性值将用于UI中该选项的显示文本。
States集合中的项没有值和文本属性,但具有StId和StName属性。因此,我们需要将此类型转换为SelectListItem类型。
所以你的代码应该是
<select asp-for="StId" asp-items="@(new SelectList(Model.States,"StId","StName"))">
<option>Please select one</option>
</select>附加参考
https://stackoverflow.com/questions/39236130
复制相似问题