2017-07-25 41 views
1

我試圖選擇一個項目將它的價格寫入輸入,以便我可以計算稅金和東西。ASP.NET選擇一個項目並顯示它的價格DropDownListFor

我設法填充DropDownList,但無法弄清楚如何獲得它的值。

到目前爲止我的代碼:

視圖模型

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; 
     } 
    } 

查看

<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> 

控制器

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

回答

1

使用jQuery聽下拉的變化,並得到目前選擇用戶更改後刪除值:

<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> 
相關問題