3

Starting out with MVC4 and Razor forms but having trouble showing a calculated field in the form - prior to submitting the form.

Say, for simplicity sake, we have fields Price and Quantity which are editable textboxes and a third readonly textbox to show the calculated total Price * Quantity.

This post suggests it's nice and easy with our newfangled Razor but when we try the below absolutely nothing changes dynamically on the form:

@{
   var value = model.Item.Value;
   var price = model.Item.Proce;
   var calculated = value * price;
}

<div class="price">Your price: @calculated</div>
Community
  • 1
  • 1
hawbsl
  • 15,313
  • 25
  • 73
  • 114

1 Answers1

5

If you want it to be real time as the user types or before submitting the form you're going to have to use javascript; server-side razor code will not be enough. The razor code will only be executed when the page is first rendered.

You have a few options:

  1. As the user is done typing send the data to the server via ajax to get a calculated total. Take the response and display it on the page
  2. Just update the calculation completely on the client as the user types (you could use a MVVM framework to help with this (e.g. Knockout.js))

Edit

Adding some links to examples:

Here is an example for #1: Making a Simple Ajax call to controller in asp.net mvc

Here is an example of how you could achieve #2: http://knockoutjs.com/examples/cartEditor.html

Personally I would do the calculation on the client (#2) and just do your validation server-side since that's where it matters.

Community
  • 1
  • 1
Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124