Rehan Khan Rehan Khan - 6 months ago 10
Javascript Question

JavaScript not firing method in the controller

I'm trying for the following code to fire an Action method in the controller.

<script>
function updateSalary() {
var salary = $('#basicSalary').val();
var figure = $('#allowance').val();
$.ajax({
url: '@Url.Action("updateSalary","salary")',
type: "GET",
dataType: "JSON",
data: { salary: basicsalary, figure: allowance },
success: function (add) {
$('#basicSalary').val(salary)
}
})
}
</script>


Razor:

<td>
@Html.DropDownListFor(model => model.allowance, Model.allowances, "--please choose an option--", new { @class = "form-control", @onchange = "updateSalary()" })
</td>


Controller:

public ActionResult updateSalary (int salary, string figure)
{
if (figure == "Transport")
{
try
{
allowance trans = hc.allowances.First(x => x.name == figure);
if (trans != null)
salary = +Convert.ToInt32(trans.amount);
else
throw new excep("Record not found");
}
catch
{

}
}
return Json(salary,JsonRequestBehavior.AllowGet);
}


Basically
allowance
should get added to
basicSalary
field on the webpage when user selects the
allowance
dropdownlist. I've put a breakpoint on starting braces of
updateSalary
Action method to check if javaScript is firing it in the controller or not when I change the selection in
allowance
dropdownList. It is not firing. I can't figure out why. Could someone see why?

Answer

Some typos here:

data: { salary: basicsalary, figure: allowance }

should probably be:

data: { salary: salary, figure: figure }

given the names of the variables you declared at the beginning of your updateSalary javascript function.

In order to track this kind of problems I would recommending you using the developer toolbar of your browser. For example if you are using Google Chrome you could click F12 to activate it and then in the Console tab look for javascript errors. Also when dealing with AJAX queries like you do, you could look at the Network tab which will show you all requests sent to the server as well as the corresponding response. This could give you a good indication where the problem might be.

Comments