将空变量传递给 MVC 控制器

Pass null variable to MVC Controller

我想将一个值 (1) 传递给我的控制器,如您所见:

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

脚本:

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

这是我的控制器

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

但是当我点击按钮时,动作被触发但是我的动作中的 refid 是空的,为什么?

而不是 $.getJSON(),试试这个代码:

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

注意:虽然$.getJSON()在内部调用$.ajax()但是后者给你更多的灵活性- http://api.jquery.com/jQuery.getJSON/

您需要在 $.getJSON()

的第二个参数中传递值
var url = '@Url.Action("MyControllerMethod","Reception",new { area ="Admin"})';
$.getJSON(url, { refid: re }, function (data) {
    console.log(data); // returns "Controller Method call"
});

我还建议您使用 Unobtrusive Javascript 而不是用行为污染标记

<input id="myButton2" type="button" data-x="1" value="Call Controller Method" />

$('#myButton2.click(function) {
    var re = $(this).data('x');
    $.getJSON(.....
});