Call method in MVC with jQuery and parameters not working

I am trying to call an action method in an MVC application using jQuery. Basically, I want to accept the value of several input fields and call the action method by pressing the button, passing the values ​​of the input fields as parameters. But I get only the value of the number parameter, not the year.

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 warning url as you can see, and both values ​​seem to be 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 this looks weird, not just binding fields, but the reason is that these input fields and their values ​​are not the main purpose of this view. They just want to choose another week in this app for a schedule. Also, I'm going to replace input fields with jQuery calendars, so I still have to do something.

So, what is the easiest way to do this, and why doesn't it work the way it is?

+4
source share
2 answers

I usually use the second jQuery parameter of the $ .get method to enter URL parameters. Here is the 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/

+6
source

Try it 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'); }); 
+6
source

Source: https://habr.com/ru/post/1333512/


All Articles