动态类别选择

本文关键字:选择 动态 | 更新日期: 2023-09-27 18:29:46

所以我有一个下拉列表,用户可以在其中选择一个类别。但我想让它更容易被用户使用,这样它就会自动选择category id并将其发布在该类别中。

我的cshtml:

<div class="form-group">
    @Html.LabelFor(model => model.category.Id, "category", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
    @Html.DropDownList("CategoryId", null, htmlAttributes: new { @class = "form-control", required = "" })
    @Html.ValidationMessageFor(model => Model.category, "", new { @class = "text-danger" })
</div>

我的控制器:

public ActionResult Create()
{
    ViewBag.CategoryId = new SelectList(db.Categorys, "Id", "Title", db.Categorys);
    return View();
}
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Title,CategoryId,Content")] Thread thread)
{
    if (ModelState.IsValid)
    {
        thread.ApplicationUserId = User.Identity.GetUserId();
        db.Threads.Add(thread);
        db.SaveChanges();
        return RedirectToAction("Post", new { @id = thread.Id });
    }
    ViewBag.CategoryId = new SelectList(db.Categorys, "Id", "Title", thread.Id);
    return View(thread);
}

我应该做些什么来使它成为动态的,这样用户就不必选择category id,而是select元素自己选择。

动态类别选择

使用DropDownListFor并指定适当的模型属性来存储您的valun,它将为您执行此操作。

@Html.DropDownListFor(m => m.CatId, Model.List, null)其中CatId是模型中的属性,List是要在select元素中显示为值的项的列表。代替第三个参数中的null,您可以为该元素指定其他html属性(例如idclass