lincx
lincx

Reputation: 409

JQuery and MVC POST

I have a html element which binded to a model (using MVC3)

        <label id="total-amount">
             @Html.Encode(@Model.TotalAmount)
        </label>

I am modifying the value using Jquery in the client side

        if (!$(this).is(':checked')) {

           var lblTotalAmount = $("#total-amount");
           var totalAmount = nationalPrice + recurPrice;
           lblTotalAmount.text(totalAmount.toFixed(2));

        }

It works fine. But when I'm posting the value of the Model.TotalAmount in my controller.. the value I modified through JQuery doesnt reflect...

    [HttpPost]
    [ActionName("Payment")]
    public ActionResult PaymentViaPost(PaymentVM viewModel)
    {
        //still the same value before JQuery modification
        var totalAmount = viewModel.TotalAmount; 

Am I missing something here like I need an async call using AJAX or something... and if it does How do I do that?

Upvotes: 1

Views: 265

Answers (2)

Misam
Misam

Reputation: 4389

I believe this can be acheived in following manner:

  1. Update html control value from client side as you have done
  2. Use $.Post of jQuery to send the updated value to a MVC controller (create a new controller to update the model)
  3. Update your model inside the controller action

Once the model is updated it will reflect on your UI. The problem in your case is that your model is not updated hence PaymentViaPost action will always fetch old values from model

Following links could help

MVC3 and jQuery

Update model with jQuery

Upvotes: 0

StanK
StanK

Reputation: 4770

Text in a label will not be sent to the server, you will need to use some sort of input control.

I'd suggest that you use a hidden control, and have your JQuery update both the label and the hidden input.

e.g.

@Html.HiddenFor( x => x.TotalAmount)
<label id="total-amount">
     @Html.Encode(@Model.TotalAmount)
</label>

if (!$(this).is(':checked')) {
   var lblTotalAmount = $("#total-amount");
   var totalAmount = nationalPrice + recurPrice;
   lblTotalAmount.text(totalAmount.toFixed(2));

   var hiddenInput = $("#TotalAmount");
   hiddenInput.val(totalAmount);   
}

Upvotes: 1

Related Questions