将 Id 从所选项目传递给控制器
Passing Id from selected item to Controller
我的视图上有一个脚本,用于将 Id 从所选值传递到我的控制器:
<script type="text/javascript">
$('#Group').change(function () {
var selectedGroup = $("#Group").val();
var categoriesSelect = $('#Category');
categoriesSelect.empty();
if (selectedGroup != null && selectedGroup != '') {
$.getJSON('@Url.Action("GetCategories")', { Id: selectedGroup }, function (categories) {
if (categories != null && !jQuery.isEmptyObject(categories))
{
categoriesSelect.append($('<option/>', {
value: null,
text: ""
}));
$.each(categories, function (index, category) {
categoriesSelect.append($('<option/>', {
value: category.Value,
text: category.Text
}));
});
};
});
}
});
</script>
这是我控制器上的功能:
[HttpGet]
public ActionResult GetCategories(int groupId)
{
//...
}
选择更改事件有效,但随 Get 请求发送的参数 groupId 始终为 0。我忘记了什么?
更新 cjp 的回答成功了。
我的第二个问题,现在过滤正在工作我 运行 进入另一件事......
我是 javascript 的新手,但当我更改所选内容时,我在第二个 DropDownList 中看到正确的数量,但为空,文本未显示..
[HttpGet]
public ActionResult GetCategories(int groupId)
{
return Json(GetCategoriesByGroupId(groupId)/*, JsonRequestBehavior.AllowGet*/);
}
这有什么问题?
$.each(categories, function (index, category) {
categoriesSelect.append($('<option/>', {
value: category.Value,
text: category.Text
}));
});
{ Id: selectedGroup } 表示您正在传递一个名为 Id 的参数,该参数在您的方法中不存在。
将其替换为 {groupId : selectedGroup } 或将您的方法签名更改为:
public ActionResult GetCategories(int Id)
我的视图上有一个脚本,用于将 Id 从所选值传递到我的控制器:
<script type="text/javascript">
$('#Group').change(function () {
var selectedGroup = $("#Group").val();
var categoriesSelect = $('#Category');
categoriesSelect.empty();
if (selectedGroup != null && selectedGroup != '') {
$.getJSON('@Url.Action("GetCategories")', { Id: selectedGroup }, function (categories) {
if (categories != null && !jQuery.isEmptyObject(categories))
{
categoriesSelect.append($('<option/>', {
value: null,
text: ""
}));
$.each(categories, function (index, category) {
categoriesSelect.append($('<option/>', {
value: category.Value,
text: category.Text
}));
});
};
});
}
});
</script>
这是我控制器上的功能:
[HttpGet]
public ActionResult GetCategories(int groupId)
{
//...
}
选择更改事件有效,但随 Get 请求发送的参数 groupId 始终为 0。我忘记了什么?
更新 cjp 的回答成功了。
我的第二个问题,现在过滤正在工作我 运行 进入另一件事...... 我是 javascript 的新手,但当我更改所选内容时,我在第二个 DropDownList 中看到正确的数量,但为空,文本未显示..
[HttpGet]
public ActionResult GetCategories(int groupId)
{
return Json(GetCategoriesByGroupId(groupId)/*, JsonRequestBehavior.AllowGet*/);
}
这有什么问题?
$.each(categories, function (index, category) {
categoriesSelect.append($('<option/>', {
value: category.Value,
text: category.Text
}));
});
{ Id: selectedGroup } 表示您正在传递一个名为 Id 的参数,该参数在您的方法中不存在。 将其替换为 {groupId : selectedGroup } 或将您的方法签名更改为:
public ActionResult GetCategories(int Id)