Pass selected DropDown value to the controller

大兔子大兔子 提交于 2020-01-23 12:30:30

问题


I have a DropDownList and a button on my View. On click of a button, I want to pass the selected DropDown value to the controller. How to do this?

View code is as below:

@model Sample2.Models.LeaveType
@{
    ViewBag.Title = "Status of Application";
}

@{
    List<SelectListItem> listItems = new List<SelectListItem>();
    listItems.Add(new SelectListItem
         {
             Text = "All",
             Value = "A",
             Selected = true
         });
    listItems.Add(new SelectListItem
         {
             Text = "Recommended",
             Value = "R"
         });
    listItems.Add(new SelectListItem
         {
             Text = "Sanctioned",
             Value = "S"
         });
}

<table>
    <tr>
        <td>
            @Html.DropDownListFor(model => model.LeaveType1, listItems, "-- Select Status --")
        </td>
        <td>
            @using (Html.BeginForm("Index", "Home", FormMethod.Get))
            {
                <input type="submit" value="Show" />
            }
        </td>
    </tr>
</table>

Controller code is like this:

    public ActionResult Index(string Id)
    {
        using (var context = new Admin_TestEntities())
        {
            var data = context.Leave_GetDetails(Id).ToList();
            return View(data.AsEnumerable().ToList());
        }

    }

** Edited **

After suggestions, I changed the code as below and it is working:

        @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        {
            @Html.DropDownList("Id", listItems)
            <input type="submit" value="Show" />
        }

回答1:


you can do it like that:

[Post]
public ActionResult Index(string fromList)
{
    ...
}

the view can look something like this:

<div>
@Html.BeginForm("Index", "Home", FormMethod.Post)
{
     @Html.DropDownListFor(model => model.LeaveType1, listItems, "-- Select Status --")
     <input type="submit" />
}
</div>


来源:https://stackoverflow.com/questions/29889165/pass-selected-dropdown-value-to-the-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!