MTplus MTplus - 8 days ago 5
Javascript Question

mvc post using javascript and display result without complete postback

I have a mvc page where the user select values from 3 different dropdown lists and then enter a number in a textfield, based on those selections and the entered number I want to do some calculations and then display the result to the user without the whole page being posted again. I understand that this can be solved using javascript, but I'm not to good in writing javasript so I could use some help here on what I need to add in order to get this to work. When I click the sumbmit button the page reloads and it does not enter the "DoCalculation" method... What am I doing wrong here?

<form name="myForm">
<div class="form-section col-md-12">
<h3 class="title_contanier">1: </h3>
@Html.DropDownList("PrintType", ViewData["printType"] as List<SelectListItem>, new { @class = "form-control" })
</div>

<div class="form-section col-md-12">
<h3 class="title_contanier">2: </h3>
@Html.DropDownList("Papper", new SelectList(string.Empty, "Value", "Text"), "-", new { @class = "form-control" })
</div>


<div class="form-section col-md-12">
<h3 class="title_contanier">3: </h3>
@Html.DropDownList("PapperType", new SelectList(string.Empty, "Value", "Text"), "-", new { @class = "form-control" })
</div>

<h3 class="title_contanier">Antal: </h3>
<input type="text" placeholder="Skriv in antal" name="Qty" id="Qty">
<button type="button" id="submitBtn">skicka</button>

<span id="resultMessage"></span>
</form>


<script type="text/javascript">
jQuery(document).ready(function ($) {
$('#PrintType').change(function ()
{
$.getJSON('/Home/GetPapperByTypeId/?typeId=' + $('#PrintType').val(), function (data)
{
var items = '<option>Välj papper..</option>';
$.each(data, function (i, printtype)
{
items += "<option value='" + printtype.Value + "'>" + printtype.Text + "</option>";
});
$('#Papper').html(items);
});
});

$('#Papper').change(function ()
{
$.getJSON('/Home/GetOptions/?ppai=' + $('#Papper').val() + '&tid=' + $('#PrintType').val(), function (data)
{
var items = '<option>Välj option</option>';
$.each(data, function (i, pappertype)
{
items += "<option value='" + pappertype.Value + "'>" + pappertype.Text + "</option>";
});
$('#PapperType').html(items);
});
});
});
</script>


<script type="text/javascript">
jQuery(document)
.ready(function($) {
$('#submitBtn').on("click", function () {
var papper = $('#Papper :selected').val();
var papperType = $('#PapperType :selected').val();
var qty = $('#Qty').val();

var request = {
"method": "POST",
"url": "@Url.Content("/Home/DoCalculation/")",
"data": { "Order": { "Papper": papper, "PapperType": papperType, "Qty": qty } }
}

$.ajax(request)
.success(function(response) {
if (response.success == true) {
$('#resultMessage').text(response.result);
}
});
});
})
</script>



public ActionResult Index()
{
ViewData["printType"] = Repository.GetAllPrintingTypes();
return View();
}

public class PapperOrder
{
public string Papper { get; set; }
public string PapperType { get; set; }
public int Qty { get; set; }
}

public ActionResult DoCalculation(PapperOrder order)
{
var papper = order.Papper;
var papperType = order.PapperType;
var qty = order.Qty;
var model = new CalculatedPrice { Totalsum = qty };
return Json(model, JsonRequestBehavior.AllowGet);
}

Answer

You can do it by simple JQuery AJAX request .

var papper = $('#Papper :selected').val();
var papperType = $('#PapperType :selected').val();
var qty = $('#Qty').val();

var request = {
  "method" : "POST",
  "url"    : "@Url.Content("ControllerName/DoCalculation")",
  "data"   : { "Order":{ "Papper" : papper,"PapperType":papperType,"Qty" : qty}},
}

$.ajax(request)
 .success(function(response){
 //do whatever you want to do with data
})

You can also make things easier by creating a model on your server side, call it PapperOrder

    public class PapperOrder {

    public string Papper {get;set;}
    public string PapperType {get;set;}
    public int Qty {get;set;}
  }

Now update your controller as follows

  public ActionResult DoCalculation(PapperOrder order){
      var Papper = order.Papper;
      var PapperType = order.PapperType;
      var Qty = order.Qty;
   // do further calculations here
  }

As you asked how to display the calculated result in success method than follow the following points.

  1. You must return Json from your controller action "DoCalculation" like below

       public ActionResult DoCalculation(PapperOrder order){
    
         //after calculation
    
         return Json(new {success = true, result = "12 (or whatever your calculated value is)"});
       }
    

Now inside your AJAX success method you can do anything, I suppose that you want to display the result inside a div so create that div

<div id="result"></div>

and inside your success method

   success:function(response){
     if(response.success == true){
        $('#result').text(response.result);
      }
    }