ajax - 从 Asp.net MVC 视图页面返回带有 Ajax 调用的视图的调用控制器方法
问题描述
我正在使用 .Net core 2.1 应用程序,在 for 循环中如何触发控制器视图页面而不返回 ajax 响应,请参见以下代码
这是我的剃刀观点
@foreach (var item in Model.CategoryList)
{
<div class="col-sm-6 col-md-4 mb-4 mb-lg-0 col-lg-2" onclick="SelectCategory(@item.CategoryId)">
<a href="#" class="popular-category h-100">
<span class="icon"><span class="@item.Icon"></span></span>
<span class="caption mb-2 d-block">@item.CategoryName</span>
<span class="number">32,891</span>
</a>
</div>
}
<script>
function SelectCategory(id) {
$.ajax({
type: 'POST',
url: '@Url.Action("ProductsList","Home")',
dataType: 'json',
data: { parentId: id }
});
}
</script>
public ActionResult ProductsList(int parentId)
{
List<PilCategory> all = new List<PilCategory>();
if(parentId > 0)
all = _context.PilCategory.Where(x=>x.ParentId == parentId).OrderBy(a => a.ParentId).ToList();
else
all = _context.PilCategory.OrderBy(a => a.ParentId).ToList();
return View(all);
}
请有人帮助我,谢谢提前
解决方案
如何在不返回 ajax 响应的情况下触发控制器视图页面
据我所知,如果不返回 ajax 响应,我们就无法触发控制器视图页面。由于 ajax 会将请求发送到控制器视图,并且控制器视图会将视图作为 html 响应返回给 ajax。
如果我们不处理响应,这意味着当前页面不会改变。
如果您只是想将 parentId 传递给 ProductsList 方法,我建议您可以尝试使用window.location
,这将使该页面重定向到 ProductsList 视图,从而实现刷新整个页面。
注意:如果我们使用ajax调用ProductsList,整个页面不会刷新。如果我们使用window.location
,它将重定向到另一个页面或刷新整个页面。
有关如何实现此目的的更多详细信息,您可以参考以下代码:
@section Scripts{
<script>
function SelectCategory(id) {
location.href = "/Home/ProductsList?parentId=" + id;
}
</script>
}
如果您想使用 ajax 来实现这一点,我建议您可以尝试使用 ajax 成功方法来处理响应。通常,我们会在控制器方法中返回部分视图,然后我们可以使用 jquery 将其添加到 html 页面中,而无需刷新页面。
有关如何实现此目的的更多详细信息,您可以参考此答案。
推荐阅读
- c# - 数据表单元格数学
- mysql - 优化数据库中大表的查询(SQL)
- powershell - 忽略Powershell中文本字符串中的引号
- javascript - 如何将 Codepen 脚本添加到我的文件中(见截图)
- html - 需要帮助将图像集中在我的标题列表中吗?
- flutter - Flutter on VS Code 运行卡在“Installing build\app\outputs\apk\app.apk...”
- css - 文件拖放到元素上后使用 :hover CSS 规则闪烁元素
- python - 如何为 Pandas 中同一类别的每条记录添加均值?
- docker - 只有一个 ubuntu docker 容器来装我需要的一切是不是错了?
- mongodb - 如何从MongoDB中对象的对象数组中查找记录