Wrong binding in <select> ASP.NET MVC <option>

Asked

Viewed 50 times

0

When I give a post in the form for the Controller, the Binding in asp-for="VehiclePlate" picks up the value of option of select (@vehicle.Category). However, I want to catch the text of option of select (@vehicle.Plate) in the Controller. How do I do it?

That’s the select:

@model Exam
...
<select asp-for="VehiclePlate" id="listVehicle" data-init-plugin="select2" style="width: 100%">
    @foreach (var vehicle in ViewBag.Vehicles)
    {
       <option value="@vehicle.Category">@vehicle.Plate</option>
    }
</select>

That’s the Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Exam exam)
{
  ...
}
  • Do you need the category for any other reason on the screen? If it’s not just you assign the card in value too... <option value="@Vehicle.Plate">@Vehicle.Plate</option>

  • That’s exactly it, I need the category.

  • Do you want to post the category, and in the controller recover the card or do you need the category by other conditions in the view? put your Exam class in question, it is an entity or viewmodel?

  • I need the selected card in the Controller. I want Binding to happen with the card and not with the category. I need the category to show in the View at any given time. And Exam class is a Viewmodel.

  • The easiest way then is to receive the category in the post and in the controller recover the card by it.

  • Not possible because a category may belong to more than one board.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.