Search code examples
javascriptasp.net-mvcjsonresult

Pass null variable to MVC Controller


I want to pass a value (1) to my controller as you can see :

<input id="myButton2" type="button" value="Call Controller Method" onclick="myff('1');"  />

Script:

function myff(re) {
  $.getJSON('@Url.Action("MyControllerMethod","Reception",new {  area ="Admin"})', function (data) {
    refid = re;
  });
}

Here is my controller

public JsonResult MyControllerMethod(string refid) {
  return Json("Controller Method call", JsonRequestBehavior.AllowGet);
}

But when I clicked the button the action is fired but the refid in my action is null why ?


Solution

  • You need to pass the value in the 2nd argument of $.getJSON()

    var url = '@Url.Action("MyControllerMethod","Reception",new { area ="Admin"})';
    $.getJSON(url, { refid: re }, function (data) {
        console.log(data); // returns "Controller Method call"
    });
    

    I also recommend you use Unobtrusive Javascript rather than polluting markup with behavior

    <input id="myButton2" type="button" data-x="1" value="Call Controller Method" />
    
    $('#myButton2.click(function) {
        var re = $(this).data('x');
        $.getJSON(.....
    });