You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中获取MVC控制器Action返回的布尔值?

常规实现步骤

1 先给控制器Action配置请求特性

首先给你的Action加上请求类型和路由配置,示例:

[HttpGet] // 如果参数是敏感内容建议用[HttpPost]
[Route("[controller]/[action]")]
public async Task<bool> CheckSurfaceOnDB(/* 你的入参 */)
{
    Surface surface = await ratesRepo.FindOneVolMatrix(/* 你的入参 */) as Surface;
    return surface != null;
}

2 在cshtml脚本中通过AJAX调用获取返回值

原生Fetch实现(无需引入额外库)

// 把你的入参拼接成查询字符串,POST请求则放到body里
const params = new URLSearchParams({
    param1: 'xxx',
    param2: 'xxx'
})
fetch(`/Home/CheckSurfaceOnDB?${params}`)
    .then(res => res.text()) // 直接返回bool默认是text格式的"True"/"False"
    .then(resStr => {
        const isExists = resStr === 'True' // 注意C#返回的布尔字符串首字母大写
        // 拿到值后执行弹窗逻辑
        if(isExists){
            alert('surface存在')
            // 替换为你的自定义弹窗逻辑
        }
    })
    .catch(err => {
        console.error('请求失败', err)
    })

jQuery AJAX实现(如果项目已引入jQuery)

$.ajax({
    url: '/Home/CheckSurfaceOnDB',
    type: 'get',
    data: {
        param1: 'xxx',
        param2: 'xxx'
    },
    success: function(res){
        const isExists = res === 'True'
        // 弹窗逻辑
    },
    error: function(err){
        console.error('请求失败', err)
    }
})

更优实现方案
  • 返回结构化JSON,避免解析错误:不直接返回布尔值,改为返回JsonResult,前端直接取属性值,不用处理字符串大小写问题,可扩展性更强:
    [HttpGet]
    [Route("[controller]/[action]")]
    public async Task<IActionResult> CheckSurfaceOnDB(/* 入参 */)
    {
        try
        {
            Surface surface = await ratesRepo.FindOneVolMatrix(/* 入参 */) as Surface;
            return Ok(new { exists = surface != null });
        }
        catch(Exception ex)
        {
            // 可自行补充日志逻辑
            return StatusCode(500, new { msg = "查询失败" });
        }
    }
    
    前端直接解析JSON即可:
    fetch(`/Home/CheckSurfaceOnDB?${params}`)
      .then(res => res.json())
      .then(data => {
          if(data.exists){
              // 弹窗逻辑
          }
      })
    
  • 页面初始化就需要值的场景,无需额外发请求:如果是页面加载时就要判断是否弹窗,可以直接把查询结果塞到ViewModel或者ViewBag,渲染页面时直接赋值给JS变量:
    控制器中返回视图的Action:
    public async Task<IActionResult> YourPage()
    {
        var surface = await ratesRepo.FindOneVolMatrix(/* 入参 */) as Surface;
        ViewBag.SurfaceExists = surface != null;
        return View();
    }
    
    cshtml中直接取值:
    <script>
        const surfaceExists = @Json.Serialize(ViewBag.SurfaceExists);
        if(surfaceExists){
            // 直接执行弹窗逻辑
        }
    </script>
    
  • 敏感参数场景改用POST请求:如果入参包含敏感数据,把Action改为HttpPost,参数放请求body中,不要暴露在URL里。

内容的提问来源于stack exchange,提问作者vicvid431

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:24:00