0
votes

I am looking for a way to pass currently selected model from view to controller. My select code:

<select asp-for="Product">
            @foreach (var p in Model.Products)
            {
                <option value="@p">@p.ProductName</option>  
            }
        </select>

I'm trying to bind option value @p to bind with my property below:

[BindProperty]
    public Product Product { get; set;}

But whenever after submitting my form the Product property has "null" values. Any suggestions?

2

2 Answers

0
votes

I think you can use a hidden type for this. No need to query to find ProductName after submit in list.

<input type="hidden" asp-for="ProductName" />
    <select asp-for="ProductId">
                @foreach (var p in Model.Products)
                {
                    <option value="@p.Id">@p.ProductName</option>  
                }
            </select>

<script>
        $(function () {
            $('form').submit(function () {                
                var productName = $('#ProductId option:selected').text();
                $('#ProductName').val(productName);
             });
         });
    </script>
0
votes

Usually you would pass the Id of the selected item when the form is posted. That is typically enough data to work with. However, if you really want the ModelBinder to create a Product instance from the posted values, your form fields should be named Product.ProductId and Product.ProductName. The other answer shows how to obtain the ProductName value and then assign it to a hidden field.

<select asp-for-"Product.ProductId" asp-items="Model.Products">
...
</select>

<input type="hidden" asp-for="Product.ProductName" />