简体   繁体   中英

How to get the value of "<select></select>" from a view into a Controller's "ActionResult"?

I have a tag and a button. On click of the button, an actionResult in a controller is called. Like this.

<button type="button" onclick="location.href='@Url.Action("GetAllItems", "Items")'">Get Items</button>

And here's the ActionResult

public ActionResult GetAllItems() {
        string selectedItem = string.Empty;
        ItemsRepository itemsRepository = new ItemsRepository();
        ModelState.Clear();
        return View(itemsRepository.GetAllItems());
    }

selectedItem is the variable I want to store either the selectedText or the selectedValue. But I don't know how to.

This is the <Select> tag.

<select style="width:170px" id="ItemsID" name="Items"></select>

And this is the rough function to get the different results from onChange event.

<script>
$(document).ready(function () {
    $("#ItemsID").change(function () {
        var a = $('#ItemsID option:selected').val();
        var b = $('#ItemsID option:selected').text().trim();
        var c = $('#ItemsID option:selected').index();

        alert(a);
        alert(b);
        alert(c);
    })
});

Please help.

location.href doesn't sent a POST request. What you got to do is to place a form tag with your ActionResult to make a POST request.

<form action='yourAction'>
<select name='name'></select>
<button type="submit">Get Items</button>
</form>

You can use following code to get the value of your select in the action method. Note that you must pass the name attribute of your html select element to Request.

var selectedValue = Request["Items"];

Also, make sure the button that is clicked submits a form by using code like below.

The main point is that you can only use Request object to access a html element value in C# code, provided the html element and the submit button are within the same form. If you use a button that redirects the user rather than submits a form then this will not work, so it must be a submit type button as in code below.

@using (Html.BeginForm("YourActionName", "ControllerName")) {

          <select style="width:170px" id="ItemsID" name="Items"></select>

          <input type="submit" value="Submit Data" id="btnSubmit" />

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM