【发布时间】:2016-08-30 20:00:17
【问题描述】:
我正在尝试将数据从我的数据库检索到 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; }
}
客户控制器
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 asp-for="StId" asp-items="@Model.States" class="form-control">
<option>Select State</option>
</select>
我在 Create 视图中的所有 HTML 都使用而不是我试图避免的 HTML Helpers。我只是希望能够将数据检索到标签中。
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-core-mvc tag-helpers