MVC3 Razor Html.TextBoxFor Calculated Fields

2019-04-13 00:28发布

问题:

Ultimately I would like to have calculated fields like Weight * Price.

Suppose I have in my MVC3 view:

    @Html.TextBoxFor(modelItem => item.Package.USDKg)
    @Html.HiddenFor(modelItem => item.Pricing.VolumePrice)

Am I able to calculate these directly? Or resort to JQuery? I would really like to keep pricing "hidden" even in source view if possible.

Basically, when a user enters their package weight, a price would be displayed (calculated off of hidden price point values).

Thank you for your guidance.

回答1:

Having a razor, you could do a logic just inside the mark up!

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

<div class="price>Your price: @calculated</div>

More info is here:

http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx



回答2:

Yes, you could do it like this:

function calculate(){
   var weight = parseFloat($("#Package_USDKg").val());
   var price = parseFloat($("#Pricing_VolumePrice").val());
   var calculus = weight * price;
   $("#calculus").text(calculus); //This shows the calculated field
}

$(document).ready(function(){
  calculate(); //Calculate on page load
  $("#Package_USDKg").change(calculate);  //Calculate every time weight changes
});

I'm assuming you have a div with id="calculus" to show the calculated field.

Hope this helps. Cheers