This is my view
<div class="form-group">
<label asp-for="Product.InStock">Available:</label>
<select class="form-control" id="Product.InStock">
<option value="False">No</option>
<option value="True">Yes</option>
</select>
</div>
And this is model Product.cs
[Required]
[Display(Name = "Available")]
public bool InStock { get; set; }
The problem is that the value sent to Controller method is always false, even when I choose option "Yes".
You didn't set a "name" value for your control, so it will never be posted back.
In your situation, since you're using ASP.NET Core MVC, the best way to solve this would be to use an asp-for tag helper in your select, just like you do for the label and validation control which are associated with the same "Product.InStock" attribute of your model.
<select class="form-control" asp-for="Product.InStock">
This way, ASP.NET will generate the correct id and name attributes on the control so it will bind to your model when the form posts back.
Of course, if your view's Model is directly Product (and not some ViewModel where Product is merely one property from it), then all your asp-for tags relating to InStock need to be simply asp-for="InStock" instead.
See https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms#the-select-tag-helper for more details of the tag helper for <select> controls
P.S. If you're just binding to a simple True/False bool as per your example code, a Checkbox might be the more appropriate type of form control from a usability perspective. Then the user only has to click once to set the value, instead of twice.
If you want to bind to another type, e.g. int or string, so that you can have lots of potential values for the field, and you want to dynamically populate the list of options (e.g. from database data) you can use the asp-items helper tag to tell ASP.NET to load the list from a server variable - details and an example are shown in the documentation in the link above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With