0

I have an ASP.NET MVC5 application in which I have a form which the user have to choose an option in a dropdownlist before submitting (an Ajax call to a method in a controller).

When submitting, I want to be able to access the TEXT of the option, not the Value in the Controller. How is this possible?

This is what the code in the View looks like:

<select name="adressID" id=" adressID ">
          <option>Choose Adress</option>
           @foreach (var address in @Model.Address)
                    {
                        <option value="@address.ID">@Html.Raw(address.Name)</option>
                    }
</select>

/ElC

3 Answers 3

2

There are probably a lot of different ways to solve this, but one approach is using Request Form collection and name property.

  1. Create a hidden property in the form.

    <input type="hidden" id="AddressName" name="AddressName" />
    
  2. Create a script, something like this

    function SetSelectedText(addressID) //function with parameter that takes in the ID of the dropdownlist
     {
       var selectedText = addressPageId.options[addressPageId.selectedIndex].innerHTML; //Looks up the innerHTML of the option, based on the selectedIndex
       document.getElementById("AddressName").value = selectedText; //Sets the hidden property to the text retrieved from innerHTML above
     }
    
  3. Add a onchange event in the select tag which invokes the function created and pass the id.

    onchange="SetSelectedText(this)"
    
  4. In the controller should now be able to access the text of the option by using

    string textFromOption = Request.Form["AddressName"];
    

Hope this helps. /ChrisRun

Sign up to request clarification or add additional context in comments.

Comments

0

Use whatever fires your form's submission (button click event?) to grab the selected option's text value and pass that along with the rest of the posted data. Here's how to do that via jQuery:

$('#submit').on('click', function(){
    var selectedText = $('#addressID option:selected').text();
    // pass with other values
    ...
});

Comments

0

If you're using Razor, why don't you use the following?

@Html.DropDownList("AddressName", null, htmlAttributes: new { @class = "form-control" })

Then in your controller on the GET use :

ViewBag.AddressName= new SelectList(db.Address, "Name", "Name");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.