Display the selected element from a dropdown combobox in C# ASP.NET MVC

Viewed 34

I have a dropdown combobox and a submit button in my application.

What I want to achieve is: every time the submit button is pressed, I want the item that was selected in the dropdown menu to be displayed on the page.

Here is a screenshot with the combobox and the submit button

The combobox gets the data from a database here is the code for binding if you need it :

<select name="select_box" class="selectpicker" id="select_box" data-live-search-style="begins" data-live-search="true">
    <option value="">Select Meal</option>
    @foreach(var obj in Model)
    {
        <option value="">@obj.Name</option>
    }
</select>

From what I've found after researching this problem , I found out that in Javascript there is a method : getElementById(id) which returns the element (in my case the combobox).

I wonder if there is something similar for C# or if there is an alternative?

Edit : Here is an example of the thing that I'm trying to accomplish, with some differences : instead of a combobox the input is taken from a text field.

<!DOCTYPE html>
<html>
<head>
    <script>
        function testVariable() {
            var strText = document.getElementById("textone").value;          
            var strText1 = document.getElementById("textTWO").value;
            var result = strText + ' ' + strText1;
            document.getElementById('spanResult').textContent = result;
             
        }
    </script>
</head>
<body> 
    <input type="text" id="textone" />
    <input type="text" id="textTWO" />
    <button  onclick="testVariable()">Submit</button> <br />
    <span id="spanResult">

    </span>
   
     
</body>
</html>
1 Answers

No you can't do with C# in .NET Core MVC.
you can do it only with javascript.

but if you use .Net Core Blazor, you can do like this.

<p>
    <label>
        Select one or more cars: 
        <select @onchange="SelectedCarsChanged" multiple>
            <option value="audi">Audi</option>
            <option value="jeep">Jeep</option>
            <option value="opel">Opel</option>
            <option value="saab">Saab</option>
            <option value="volvo">Volvo</option>
        </select>
    </label>
</p>

<p>
    Selected Cars: @string.Join(", ", SelectedCars)
</p>

@code {
    public string[] SelectedCars { get; set; } = new string[] { };

    void SelectedCarsChanged(ChangeEventArgs e)
    {
        if (e.Value is not null)
        {
            SelectedCars = (string[])e.Value;
        }
    }
}

https://learn.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-6.0#multiple-option-selection-with-select-elements

Related