Juan Gallardo
Juan Gallardo

Reputation: 104

How can I get the selected value from a dropdown from within a razor file in ASP.NET Core MVC

Let's say I have a view Foo.cshtml like this:

<form method="post" action="/">
  <select id="Country" name="Country">
    <option value="MX">Mexico</option>
    <option value="CA">Canada</option>
    <option value="US">USA</option>
  </select>

  <button type="submit">Register</button>
</form>

@{
  string selectedValue = ???;
  string selectedText = ???;
}

How could I go about initializing these strings?

Upvotes: 1

Views: 3025

Answers (3)

Matt Stewart
Matt Stewart

Reputation: 322

The code below only executes once at page load to assist in rendering the HTML for your view. This is true for any C# you have in your cshtml files.

@{
  string selectedValue = ???;
  string selectedText = ???;
} 

As other answers have noted, the way to dynamically retrieve the value of any input control is with JavaScript.

I'm assuming that after you've retrieve the selected value and text from the drop down that you'll want to use it for something in the partial view?

In which case, you'll need to use JavaScript for that as well.

//retrieve your values
var e = document.getElementById("Country");
var value= e.options[e.selectedIndex].value;
var text= e.options[e.selectedIndex].text;

//use them to do something 
var targetElement = document.getElementById("your-target-elements-id");
targetElement.innerHtml = 'Text:' + text + ' Value:' + value;

Upvotes: 1

Abolfazl
Abolfazl

Reputation: 1710

I think there is a misunderstanding over server side and client side in your code
lines below are rendered and paraphrased by server

@{
  string selectedValue = ???;
  string selectedText = ???;
} 

it means when it reached to the browser,its done and cannot be changed

If you want to have selected value in dropdown,you should be using javascript to get what you want not server side language

you can use javascript

var e = document.getElementById("Country");
var value= e.options[e.selectedIndex].value;
var text= e.options[e.selectedIndex].text;

or get it via jquery

$('#Country :selected').text();
$('#Country :selected').val();

Upvotes: 4

user8107351
user8107351

Reputation: 437

if I understood you correctly, you want to get the selected dropdown and pass it on to the variable below, well you could use could use javascript like so:

<form method="post" action="/">
  <select id="Country" name="Country">
    <option value="MX">Mexico</option>
    <option value="CA">Canada</option>
    <option value="US">USA</option>
  </select>

  <button type="submit">Register</button>
</form>



var getCountry = document.getElementById("Country");
var selectedValue = getCountry.options[getCountry.selectedIndex].value;

Upvotes: 2

Related Questions