gpt4 book ai didi

c# - HTML.DropDownListFor 下拉列表

转载 作者:行者123 更新时间:2023-11-30 23:21:22 24 4
gpt4 key购买 nike

我正在尝试将数据从我的数据库检索到 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; }
}

客户 Controller

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);
}
}

创建 View

下面的 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>

我在创建 View 中使用的所有 HTML,而不是我试图避免的 HTML 助手。我只是希望能够将数据检索到标签中。

最佳答案

对于选择标签助手,asp-items 需要 SelectListItem collection\SelectList,其中的每个项目都有一个 Value文本 属性。 Value 属性值将用于选项的值,Text 属性值将用于 UI 中选项的显示文本。

States 集合中的项目没有 Value 和 Text 属性,但有 StIdStName 属性。所以我们需要把这个类型转换成SelectListItem类型。

所以你的代码应该是

<select asp-for="StId"  asp-items="@(new SelectList(Model.States,"StId","StName"))">
<option>Please select one</option>
</select>

附加引用

Select Tag Helper in MVC 6

关于c# - HTML.DropDownListFor 下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39236130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com