0

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 ?

7
  • 3
    You have not passed he value to the controller - $.getJSON('@Url.Action(...)', { refid: re }function (data) { Commented Jun 11, 2018 at 7:46
  • @StephenMuecke so how can i pass the value ? Commented Jun 11, 2018 at 7:53
  • As per my comment - you pass it in the 2nd argument of getJSON as an object Commented Jun 11, 2018 at 7:56
  • @StephenMuecke I changed to this ,but return null again $.getJSON('@Url.Action("MyControllerMethod","Reception",new { area ="Admin"})', { refid: re },function (data) { refid = re; }); Commented Jun 11, 2018 at 7:58
  • That works fine (but the { refid = re; } in the callback makes no sense. But you really need to stop polluting your markup with behavior and use Unobtrusive Javascript Commented Jun 11, 2018 at 8:01

2 Answers 2

3

Instead of $.getJSON(), try this code:

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

Note: Although $.getJSON() calls internally $.ajax() but the latter one gives you more flexibility- http://api.jquery.com/jQuery.getJSON/

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

2 Comments

I changed to this , <script> function myff(re) { $.ajax({ dataType: "json", url: '@Url.Action("MyControllerMethod","Reception",new { area ="Admin"})', data: {refid : re}, success //to do }); } </script>but my controller doesn't fire
Removed the success prameter. Try the updated answer.
2

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(.....
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.