0

I'm working on an ASP.NET MVC project.

Here is code I've been stuck on:

<select>
    <option asp-controller="Home" asp-action="Catalog" asp-route-id="1" >Fish</option>
    <option asp-controller="Home" asp-action="Catalog" asp-route-id="2">Rodent</option>
</select>

<a asp-controller="Home" asp-action="Catalog" asp-route-id="2">Click to show Category num 2</a>

The <a> tag is working, while the select doesn't.

I've tried to put it on form with Submit button and still not working.

What am I missing?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

Those asp tag helpers you are using won't do anything for <option> elements. You'll need to submit a form and give them a value. Your <select> also needs a name attribute so your action can bind to a variable.

Your form:

<form id="myForm" asp-controller="Home" asp-action="Catalog" method="get">
    <select name="id">
        <option value="1">Fish</option>
        <option value="2">Rodent</option>
    </select>
    <button type="submit">Send</button>
</form>

The controller action:

[HttpGet]
public IActionResult Catalog(int id)
{
    return View();
}

If you want to automatically send when the select changes, you'll need JavaScript. The easiest is to submit the form with js.

Add an event handler to the element

<select name="id" onchange="handleChange()">
    <option value="1">Fish</option>
    <option value="2">Rodent</option>
</select>

And define the even handler

function handleChange() {
    document.getElementById('myForm').submit();
}

Another option is to listen for the event and make an AJAX request instead of doing a form submission.

Vanilla JavaScript and jQuery examples here.

Jasen
  • 14,030
  • 3
  • 51
  • 68
  • Hi! Thank you it's worked, by the way can I make the Select to submit with out a Sumbit button? Just that the select will be. – meitar edri Nov 17 '21 at 21:08