Gustavo Ordaz
Gustavo Ordaz

Reputation: 57

ASP.NET select an item and show it's price DropDownListFor

I'm trying to select an item to write it's price into an input so I can calculate taxes and stuff.

I managed to populate the DropDownList but can't figure out how to get it's value.

My code so far:

View Model

public List<Producto> Productos;

    [Display(Name = "Producto")]
    public int ProductoId { get; set; }

    public IEnumerable<SelectListItem> ProductosItems
    {
        get 
        {
            var todosProductos = Productos.Select(f => new SelectListItem
            {
                Value = f.ID.ToString(),
                Text = f.Nombre + " - S/" + f.Pecio
            });
            return todosProductos;
        }
    }

View

<div class="form-group">
        @Html.LabelFor(m=>m.ProductoId, new { @class="col-md-2 control-label" })
        @Html.DropDownListFor(
            m => m.ProductoId,
            Model.ProductosItems,
            "-- Seleccionar --",
            new { @class = "form-control", @onchange="IDproducto();" }
        )
        @Html.ValidationMessageFor(m => m.ProductoId)
    </div>

Controller

public IActionResult Create()
    {
        VentaViewModel model = new VentaViewModel()
        {
            Clientes = _context.Cliente.ToList(),
            Productos = _context.Producto.ToList()
        };
        return View(model);
    }

Upvotes: 1

Views: 508

Answers (1)

Georg Patscheider
Georg Patscheider

Reputation: 9463

Use jQuery to listen to changes of the dropdown, and get the currently selected value after the user changed it:

<script>
$(document).ready(function() {
    // use @Html.IdFor so this does not break 
    // if you rename the ProductoId property in the ViewModel
    var dropdown = $('#@Html.IdFor(m => m.ProductoId)');

    dropdown.on('change', function () {
        // this gets the "value" attribute of the selected option
        // if you need the text, use .text() instead of .val()
        var selected = $('option:selected', dropdown).val();
        // work with selected value ...
    });
});
</script>

Upvotes: 1

Related Questions