Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass value of selected dropdown list from View to Controller in MVC

Tags:

asp.net-mvc

Hi i need some help on MVC as new in this area. Here is my code for Dropdown list and I just want to get the selected values by user in a controller so that I can pass that value to a table in db. Here is the code from .cshtml

@Html.DropDownList("LogOffTime", new List<SelectListItem>
{
    new SelectListItem{ Text="One", Value = "30000" },
    new SelectListItem{ Text="Two", Value = "60000" },
    new SelectListItem{ Text="Three", Value = "180000" }
}, "Select Time") 

Controller:

 public ActionResult Index()
 {How to get the value from drop down list}

I just need to know how to access the value i.e. the 30000/60000 etc. in controller. Also need to check that no value will be passed if the user does not select anything. Also correct me pls. if anything wrong in my code. Thanks!

like image 718
zam Avatar asked Jan 04 '23 21:01

zam


1 Answers

I have this example from what I am working right know. I hope it can help

View or DropDownList:

@using(Html.BeginForm("getSelectedValue", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.DropDownList("LogOffTime", new List<SelectListItem>
    {
       new SelectListItem{ Text="One", Value = "30000" },
       new SelectListItem{ Text="Two", Value = "60000" },
       new SelectListItem{ Text="Three", Value = "180000" }
    }, "Select Time")

    <input type="submit" value="Submit" />
}

HomeController:

[HttpPost]
public ActionResult getSelectedValue()
{
    var selectedValue = Request.Form["LogOffTime"].ToString(); //this will get selected value
}
like image 101
kielou Avatar answered May 01 '23 20:05

kielou