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

I got the Solution for above issue.

Model(MotorInput.cs)

public int CatID { get; set; }

Controller(UserController.cs) //To load in View page setting to viewBag from database

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

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">
    }

Controller(Usercontroller.cs) // After 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);
          }

This helps to get the dropdown value to controller from view.

Leave a Comment