如何将参数发送到 mvc 控制器中的 jsonresult 操作?

How to send parameter to jsonresult action in a controller in mvc?

我有一个问题困扰了我一段时间。

我的控制器 (SubSubCategoriesController) 中有一个 JsonResult 方法:-

 public JsonResult GetSubCategories(int CategoryID)
    {
        return Json((db.SubCategories.Select(p => new { CategoryID = p.CategoryID, SubCategoryID = p.SubCatgeoryID, SubCategoryName = p.SubCategoryName })).Where(p => p.CategoryID == CategoryID), JsonRequestBehavior.AllowGet);
    }

现在,我想从我的视图发送参数 (CategoryID) 的值?我怎样才能做到这一点? 提前致谢

如果您的数据不是在视图模型中构造的,我的意思是如果您只对发送单个参数感兴趣,那么您可以使用下面的 ajax 函数从视图中定义它。

$.ajax({
         type: 'GET',
         url: '<%= Url.Action("GetSubCategories") %>',
         cache: false,
         data: { CategoryID : <bind it from UI> },
         success: function (data) {
            console.log(data);  
         },
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);    
         }
});

或者另一种巧妙的方式

$.post( "controller/method", {CategoryID: "<From UI>"}, function(result) {
  console.log(result)
});

然后用 httpPost

修饰 action 方法
[httpPost]
public JsonResult GetSubCategories(int CategoryID)
{
}

$.post here