开发者

ASP.NET MVC: How to show value in a label from selected Drop Down List item?

开发者 https://www.devze.com 2022-12-21 14:12 出处:网络
I\'m trying to show a value of selected Drop Down List item in a label. I managed to make this work with Web Forms but with MVC I\'m totally lost. My Index looks like this:

I'm trying to show a value of selected Drop Down List item in a label. I managed to make this work with Web Forms but with MVC I'm totally lost. My Index looks like this:

[...] 
   <% using (Html.BeginForm()) { %>
       <table>
          <tr>
             <td>Processor</td>
             <td><%= Html.DropDownList("lstProcessor1", new SelectList((IEnumerable)ViewData["Processor1List"], "product_price", "product_description")) %></td>
          </tr>
          <tr>
             <td>Total Amount</td>
             <td>0,00 €</td>
          </tr>
         </table>
      <input type="submit" value="Submit" />
   <% } %>
    [...]

And my HomeController starts with:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        // Connect database
        DB50DataContext _ctx = new DB50DataContext();

        // GET: /Home/
        public ActionResult Index()
        {
            // Search: Processors
            var products = from prod in _ctx.products
                           where prod.product_searchcode == "processor1"
                           select prod;

            ViewData["Processort1List"] = products;

            return View();
        }

I would like the product_price to show on the second line of the table, where it now says 0,00 €. It should also update the price automatically when the item from the Drop Down List is changed.

I guess I shou开发者_开发百科ld use JQuery but I have no idea how. Could someone please give me some tips how to do this?


Change your action to put a IEnumerable<SelectListItem> into the view data instead of the actual product elements. Then change your view to simply use this list.

public ActionResult Index()
{
    // Search: Processors
    var products = from prod in _ctx.products
                   where prod.product_searchcode == "processor1"
                   select new SelectListItem { Text = prod.product_description, Value = prod.product_price };

    ViewData["Processort1List"] = products;

    return View();
}

Now for the form. Change it to use the list you created in the action without the extra code (and a default selection). Add an id to the TD that needs to be updated -- note that the value is going to come from the select when you post it, not the TD.

Processor )ViewData["Processor1List"],""Select a product") %> Total Amount 0,00 €

Now add a bit of javascript to update the TD when the select changes

<script type="javascript">
    $(function() {
        $('#lstProcessor1').change( function() {
            ('#price').html( $(this).val() );
        });
    });
</script>


You can do this with jQuery:

Add an id for your total cell:

...
             <td>Total Amount</td>
             <td id="total">0,00 €</td>
...

Then, add some JavaScript that will fire when the selection changes:

<script type="text/javascript" src="jquery-1.4.1.js"></script>
<script type="text/javascript">

$(function() {
   // Update total when the page loads. 
   $('#total').html($('#lstProcessor1').val());

   // Update total when the selection changes.
   $('#lstProcessor1').change(function() {
      $('#total').html($(this).val());
   });
});

</script>

Of course, you could optimize this code so it's not repetitious (DRY), and you would probably want to move it into an external JS file. I hope this helps.


I would suggest you adding a new action on your controller that will return the price of a product given the product id. The product id should represent the value of the dropdown:

public ActionResult Price(int? productId)
{
    decimal price = 0;
    var product = _ctx.products
        .Where(prod => prod.id == productId)
        .FirstOrDefault();
    if (product != null)
    {
        price = product.Price;
    }
    return Json(new { price = price });
}

This action will then be invoked when you change the value of the dropdown box:

$(function() {
    $('#lstProcessor1').change(function() {
        var productId = $(this).val();
        $.getJSON('/controller/price', { productId: productId }, function(json) {
            $('#total').html(json.price);
        });
    });
});


I agree with all these guys. However, there's 2 important things you should take a look at:

1) You should name your ViewData object with the same key name as the control in your view. This way, you will not need to specify in your View the actual "ViewData" object, as the MVC engine will find it.

2) Yes, you could persist your price lookups in a JSON object on the client side. But, this could get large, complex, and unruly. I would suggest making an asynchronous call with jQuery. Look into the jQuery "$.getJSON" function, and use it in conjunction with the MVC JsonResult.

Let me know if you'd like more detail :)


If you want to grab the price, or any other data, from the server you can use jquery and do tthis:

$(lstProcessor1).change(function (product) {
    $.getJSON('/products/getproduct', { id: $(this).val() }, function(product) {
        $('#product-total').val(product); // or use .html() if it's not an input element
    })
})

In your controller you just have to return a json serialized prodcut with return Json(product)

0

精彩评论

暂无评论...
验证码 换一张
取 消