Diego Unanue
Diego Unanue

Reputation: 6826

Set TextBox value from model when DropDown change in mvc

I've got a ViewModel called Bill who has a list of a model called Product, the Index view that use Bill ViewModel has a DropDown with the names of the products and a textbox where I want to set the product's price (located into the product list) into the textbox depending on the product selected in the dropdownlist.

Here is the product model:

    public class Product
    {
    public string ProductName { get; set; }
    public decimal Price { get; set; 
    }

Here is the Bill Model:

    public class BillViewModel
    {
    public SelectList ProductList { get; set; }
    public int ProductSelected { get; set; }
    public List<Product> ListProducts { get; set; }

    }

Here is the Index view:

This is the script I use to change the dropdownvalue, I use the value selected in the dropdown in the productlist to get the product price, but It gets always the first value rendered, the text box does't update the value when I change the selection.

<script type="text/javascript">

$('#select').change(function () {
    $('#priceTxt').val(@Model.ListProducts[@Model.ProductSelected].Price);
});

<fieldset>
    <legend>BillViewModel</legend>

    <div class="display-label">
        @Html.Label("Product")
        @Html.DropDownListFor(model => model.ProductSelected, Model.ProductList, "Select Product", new {id = "select"})
    </div>

</fieldset>
<div class="modal-footer">
    <a href="#" class="btn" data-dismiss="modal">Close</a>
    <a href="#" class="btn btn-primary" data-dismiss="modal" id="submit">Save changes</a>

If I don't using the correct architectural approach please let me know.

Upvotes: 0

Views: 2901

Answers (1)

Erik Noren
Erik Noren

Reputation: 4339

Your model isn't updated when the UI changes. The model just provides "intellisense" type functionality to ensure strong binding between properties and UI. It can also be used by the a model binder to map those form fields back to a concrete object when the form is submitted. Once it's rendered to the client browser though, there's no actual model anymore. It's only valid during server side rendering and binding.

You'll want to update the Change handler to grab the selected value from $(this) instead of trying to use the model where "$(this)" is the jQuery-wrapped DOM element that triggered the change event - your drop down. Just look to see how to grab the value. I can't do a code sample at the moment but it should be easy to find how to access the selected value of a drop down on change.

Edit: Think of the model properties as constant values. They are inserted into the markup at render time on the server and the result is sent on to the browser. In this case your change handler is basically sending a hard-coded value to the .val() call. It will never change once it's been rendered on the browser.

Upvotes: 1

Related Questions