2
我想從我的數據庫檢索數據到HTML而不是檢索到Html.DropDownListFor但我無法檢索到標記。HTML.DropDownListFor DropDownList
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 asp-for="StId" asp-items="@Model.States" class="form-control">
<option>Select State</option>
</select>
我所有的HTML在我的創建視圖使用,而不是HTML幫手,這是我想要避免的。我只想能夠將數據檢索到標籤。
謝謝!!這工作。我有幾個問題,「@」符號是做什麼的,爲什麼它需要? – Brian
我會更好地檢索我的控制器中的DropDownList的Value和ID數據,而不是其他方式嗎?如果是這樣,我需要添加到Create Action Method和SelectTag Helper中? '私人的IEnumerable GetStateList() { 變種STE = _context.State 。選擇性(s =>新SelectListItem { 值= s.StId.ToString(), 文本= s.StName } ) .ToList(); return(ste); }' –
Brian
你需要'@'因爲我們想執行一些C#代碼(創建新的SelectList對象)。我個人更喜歡在視圖中保留更少的C#代碼。看到我發佈的鏈接,它有不同的方法。我更喜歡C#代碼較少的代碼(在視圖中沒有新的SelectList) – Shyju