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

Razor视图中如何将C#变量与JQuery字符串拼接成URL

如何在Razor页面的JavaScript中正确拼接C#变量与字符串?

你的问题出在Razor变量没有被正确处理为JavaScript字符串常量,导致生成的URL出现语法错误。原代码中@ApiAddress直接输出值后,在JS代码里变成了裸字符串,和后续的JS字符串拼接逻辑冲突,最终生成了错误的URL格式。

解决方法1:给Razor变量添加引号,转为JS字符串常量

直接在@ApiAddress前后加上双引号,让Razor渲染后成为合法的JS字符串,再和后续部分拼接:

@{
    ViewData["Title"] = "mypage";
    string ApiAddress = "https://localhost:8114/api/";
 }

 <div>
     ...
 </div>

@section Scripts{
    <script>
        function show(id) {
        $.ajax({
            type: "Get",
            url: "@ApiAddress" + "UserApi/Getbyid=" + id,
            dataType:"json"
        });
    }
    </script>
 }

Razor渲染后,JS代码会变成:

url: "https://localhost:8114/api/" + "UserApi/Getbyid=" + id,

这样就能正确拼接出目标URL。

解决方法2:在C#中预先拼接基础URL

如果不想在JS里拼接基础部分,可以直接在Razor代码块里先组合好基础API路径,再传给JS:

@{
    ViewData["Title"] = "mypage";
    string ApiAddress = "https://localhost:8114/api/";
    // 预先拼接基础API路径
    string UserApiBaseUrl = ApiAddress + "UserApi/Getbyid=";
 }

 <div>
     ...
 </div>

@section Scripts{
    <script>
        function show(id) {
        $.ajax({
            type: "Get",
            url: "@UserApiBaseUrl" + id,
            dataType:"json"
        });
    }
    </script>
 }

解决方法3:使用Razor的Url辅助方法生成API路径(推荐)

硬编码URL不利于维护,推荐使用Razor内置的Url.Action方法生成API地址,这样即使站点地址或路由规则变化,代码也能自动适配:

@{
    ViewData["Title"] = "mypage";
 }

 <div>
     ...
 </div>

@section Scripts{
    <script>
        function show(id) {
        $.ajax({
            type: "Get",
            // 生成UserApi控制器的Getbyid方法路径,再拼接id参数
            url: "@Url.Action("Getbyid", "UserApi")" + "?id=" + id,
            dataType:"json"
        });
    }
    </script>
 }

如果你的API是RESTful风格(比如路径为/api/UserApi/Getbyid/{id}),可以这样写:

url: "@Url.Action("Getbyid", "UserApi")/" + id,

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:40:48