Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling action method in MVC with jQuery and parameters not working

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?

like image 524
Anders Avatar asked Dec 16 '22 18:12

Anders


2 Answers

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/

like image 100
rcravens Avatar answered May 13 '23 14:05

rcravens


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');
});
like image 29
Darin Dimitrov Avatar answered May 13 '23 14:05

Darin Dimitrov