BviLLe_Kid BviLLe_Kid - 4 months ago 7
Ajax Question

Ajax Values to Controller Method

I am trying to pass values to my controller, from my view using ajax. I am relatively new to using ajax so I need some help figuring this out.

Full Page

@model ALSummary.Models.MonthReport

@{
ViewBag.Title = "Index";
}

<h2><strong>Generate Monthly Report</strong></h2>

<br />
<hr />

@Html.BeginForm("Generate", "MonthReports", FormMethod.Post, htmlAttributes: new { id = "GenerateForm" }){
<div class="form-horizontal">
<div class="form-group">
@Html.Label("Choose AC:", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("AC", null, "-- Select AC --", htmlAttributes: new { id = "AC", @class = "form-control" })
</div>
</div>
</div>


<div class="form-horizontal">
<div class="form-group">
@Html.Label("Choose Month:", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Months", null, "-- Select Month --", htmlAttributes: new { id = "Month", @class = "form-control" })
</div>
</div>
</div>

<div class="form-horizontal">
<div class="form-group">
@Html.Label("Year:", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Years", null, "-- Select Year --", htmlAttributes: new { id = "Year", @class = "form-control" })
</div>
</div>
</div>

<br />

<input type="submit" id="SendToController" class="btn btn-primary" value="Generate" />
}


<script type="text/javascript">
$('#SendToController').on('click', function() {
sendToController();
return false;
});
function sendToController(){
var selectedAC = $('#AC').val();
var selectedMonth = $('#Month').val();
var chosenYear = $('#Year').val();
$.ajax({
url: @Url.Action("Generate", "MonthReports", null),
data: { 'id' : selectedAC, 'monthValue' : selectedMonth, 'year' : chosenYear },
type: 'GET',
cache: false,
success: function(data){},


});
}


</script>


Error Message:

enter image description here

Here is where the red squiggly lines are happenning when I receive the error message:

enter image description here

Answer

Your AJAX and Controller look fine... the error reported is because your javascript function can't be found (isn't present) at the time that the HTML is loaded for the Submit input (usually this is because the JS isn't loaded until after the DOM, my guess is that your script block is at the end of your body and not in the head (which is fine/preferred, just needs to be handled a bit differently)).

I typically prefer to bind events via JS rather than the HTML. Remove the onclick="sendToController()" from your HTML, and add this to your JavaScript:

$("#FormID").on('submit', function(event) {
    event.preventDefault();
    sendToController();
    return false;   // prevent submit from submitting
});

function sendToController() {
    // your other code here
}

Change FormID to the ID of the form as required.

Comments