Steve Newton
Steve Newton

Reputation: 1078

MVC3 - display price based on product selection in form

I am sure there will be articles around this but I really don't know the correct name for it and having little success finding examples like mine.

I have a quote form where you have the ability to select a product and atributes of it. There are three dropdowns and based on the combination of the three, I have a table (with associated model/controller) that has a price. I want to display the price on the page but i must update as the selections are updated.

Setting the price from the get go seemed easy but then updating it based on dropdowns selected had me go in a tail spin of '"onSelectedIndexChanged()', javascript, AJAX, partial views and I simply confused myself.

I need a simple way to display price information on a quote form as they fill out the details (three fields control price). I did look at the music store demo but its slightly different and the shopping cart element which looked handy was grabbing data in a table so again got stuck.

Help always appreciated as ever.

Thanks, Steve.

Upvotes: 1

Views: 694

Answers (1)

tvanfosson
tvanfosson

Reputation: 532505

When one of the three dropdowns changes, I'd make an AJAX call to the server to get the price as a JSON object and use it to update the price input.

Example using jQuery to add the handlers and perform the AJAX operation.

var $priceControls = $('#control1,#control2,#control2');
$priceControls.change( function() {
     $.getJSON( '@Url.Action("price","product")',
                $priceControls.serialize(),
                function(price) {
                    $('#price').val(price);
     });
});

public class ProductController : Controller
{
     public ActionResult Price( string control1, string control2, string control3 )
     {
         decimal price = ...lookup price based on control values...
         return Json( price, JsonRequestBehavior.AllowGet );
     }
}

Upvotes: 1

Related Questions