Search code examples
asp.net-mvcdrop-down-menuviewselectedvalue

How to get the selected value of a dropdown in the MVC View itself


I have a drop down in a MVC View, which is some thing like this:

Html.DropDownList(id, Range(0,10)
                        .Select(x => new SelectListItem {Text = x, Value = x}))

In the view itself, I need the selected value of this drop down. I know that I can access that in a JavaScript, but I am looking for a way to get it in the view itself from the drop down properties or something like that.

How can I access it? I tried to figure out some thing from intellisense but nothing relavant showed up, help is much appreciated.

Edit: I want the value after a few lines after the declaration of the drop down, I know that I can access it from JavaScript and by posting the form, Is there noway to access it on the view itself ?

Edit2: If its not possible to access it in view, please explain the reason, I am more interested in knowing it.

Thanks.


Solution

  • After reading at your question, it sounds like you want to have the drop down list supply a value for a lower section of the same page.

    First and foremost, you will need to place the DropDownList within a form construct, as in:

    <% using (Html.BeginForm("ProcessValue", "ThisPage")) { %>
        <%= Html.DropDownList("DropID", Range(0, 10).Select(a=>new SelectListItem { Text = x, Value = x }) %>
        <input type=submit value="Submit" />
    <% } %>
    

    You need to set up a few things ahead of time:

    1. You have to have a submit button, or a similar construct, in order to retrieve the value of the DropID variable.
    2. You need to set up an controller method that will handle the processing of the value, then redirect back to the original page with the selected value in the page's ViewData.
    3. Finally, you need to set up the view so that the post-processing section will only display if you have a valid value in the DropID variable.

    It's not as simple as just placing a DropDownList in a view and then using that value later on in the page. You have to get the controller involved to manage the data transport and you have to set up the single view to handle multiple states (ie. before the value is selected and after the selection takes place).