I'm trying to call an action method in an MVC application using jQuery. Basically what I want is to take the value of a couple of input fields and call the action method by clicking a button, passing the values of the input fields as parameters. But I only get the value of the "number" parameter, not the "year" parameter.
function selectWeek() {
$('#selectWeekButton').click(function (event) {
var number = $("#selectWeekId").val();
var year = $("#selectYearId").val();
var actionUrl = '<%: Url.Action("Edit", new { number="WEEKPLACEHOLDER", year="YEARPLACEHOLDER" }) %>'
var yearUrl = actionUrl.replace('YEARPLACEHOLDER', year);
var url = yearUrl.replace('WEEKPLACEHOLDER', number);
alert(url);
$.get(url, function (data) {
alert('Test');
});
});
}
I checked the url with an alert, as you can see, and it seems to contain both values fine. But when I check the value of the year parameter in the action method it is null.
Here are the input fields:
<span>Vecka: </span>
<input type="text" id="selectWeekId" />
<span>År: </span>
<input type="text" id="selectYearId" />
<input type="button" value="Välj vecka" id="selectWeekButton" />
And the beginning of the action method:
public ActionResult Edit(string number, string year)
//etc...
I know that this looks like a strange thing to do instead of just binding fields, but the reason is that these input fields and their values is not the main purpose of this View. They're just there to select another week in this timesheet application. And besides, I'm going to replace the input fields with a jQuery calendar eventually, so I will still have to do something like this.
So what's the easiest way to do this, and why isn't it working as it is?
I usually use the jQuery second parameter of the $.get method to enter the URL parameters. Here is a post (asp.net mvc 1 but still a valid example):
http://blog.bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/
Try like this:
var number = $('#selectWeekId').val();
var year = $('#selectYearId').val();
var url = '<%: Url.Action("Edit") %>';
$.get(url, { number: number, year: year }, function (data) {
alert('Test');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With