4

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?

1
  • Not sure but I think its a routing issue. Commented Dec 27, 2010 at 23:01

2 Answers 2

6

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful! It seems so obvious now that I see it, I guess I'm just not familiar enough with jQuery yet to see these things. Thanks a lot!
6

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');
});

1 Comment

Good example. Unfortunately rcravens beat you to it, same idea :-p But thanks a lot anyway!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.