如何在控制器的 [HttpPost] 中获取 @DropDownListFor 的值

How to get the value of @DropDownListFor in [HttpPost] at controller

我无法将@Html.DropDownListFor 的值获取到控制器。 我是 MVC 的新手。 我在这里添加代码。

型号

 public IEnumerable<System.Web.Mvc.SelectListItem> CatID { get; set; }

控制器

public ActionResult Motors()
{
 ViewBag.CatID = new SelectList(db1.motors.ToList(), "id", "cat");
 return View();
}

查看

//(鉴于 DATA 正在从数据库正确加载)

 @Html.DropDownListFor(m => m.CatID, ViewBag.CatID as SelectList, new { @class = "form-control" })

控制器在post后返回控制器)

[HttpPost]

    public ActionResult Motors(MotorInput collection)

         {
            MotorInput obj = new MotorInput
               {
               CatID = collection.CatID
               }; 
              return View(collection);
         }

我只是在寻找一种方法来获取从视图到控制器中选择的@Html.DropDownListFor 的值。

Screenshot of Model

Screenshot of Controller after post

我得到了上述问题的解决方案。

型号(MotorInput.cs)

public int CatID { get; set; }

Controller(UserController.cs) //从数据库加载View页面设置到viewBag

public ActionResult Motors()
        {
            this.ViewBag.CatID = new SelectList(this.db1.motors, "id", "cat");
            return View();
        }

查看(Motors.cshtml)

@model BLL.Models.MotorInput
@{
    ViewBag.Title = "Motors";
    Layout = "~/Views/Shared/_UserLayout.cshtml";
}

    @using (Html.BeginForm())
    {
         @Html.DropDownList("CatID", (SelectList)ViewData["CatID"], "-- Select Category --", new { @class = "form-control" })


     <input type="submit" value="Create">
    }

控制器(Usercontroller.cs) // 在post.

之后
[HttpPost]
public ActionResult Motors(MotorInput collection)// MotorInput is the class where CatId is set as int.(Model class)
           {
             MotorInput obj = new MotorInput
                       {
                           CatID = collection.CatID,
                       };
                    return View(collection);
          }

这有助于从视图中获取控制器的下拉值。