如何将Razor页面的HTML内容赋值给JavaScript变量?
解决Razor页面动态插入局部视图内容的问题
方案一:通过AJAX请求后端获取局部视图HTML
适合需要动态生成带数据内容的场景,步骤如下:
创建局部视图
将需重复添加的内容存入Section.cshtml局部视图:<div class="text-box-section"> <input type="text" placeholder="新增文本框" /> <!-- 其他Razor内容 --> </div>添加后端接口
在控制器中新增Action,返回该局部视图的HTML:public IActionResult GetSection() { // 如需传递模型数据,可在此构造并传入PartialView return PartialView("~/Views/Section.cshtml"); }修改前端JS函数
用fetch请求接口获取HTML后插入页面:async function addNewSection() { const section = document.getElementById("lastTextBox"); const response = await fetch('/ControllerName/GetSection'); const newSectionHtml = await response.text(); section.insertAdjacentHTML('afterend', newSectionHtml); }注意替换
/ControllerName/GetSection为实际接口路由。
方案二:预渲染隐藏模板复用
如果新增内容无需动态数据,可提前渲染隐藏模板,JS直接复用:
在主页面预渲染模板
在主Razor页面的合适位置(如底部)添加隐藏容器:<div id="sectionTemplate" style="display: none;"> @{ Html.RenderPartial("~/Views/Section.cshtml"); } </div>修改前端JS函数
直接复制模板内容插入目标位置:function addNewSection() { const section = document.getElementById("lastTextBox"); const template = document.getElementById("sectionTemplate"); const newSection = template.firstElementChild.cloneNode(true); section.insertAdjacentElement('afterend', newSection); }
原方法报错原因
你之前尝试的var newSection = @RenderPage("~/Views/Section.cshtml");存在两个问题:
RenderPage返回的HTML包含换行、引号等特殊字符,直接嵌入JS会破坏语法结构,导致解析错误。- Razor表达式树不允许动态操作,
RenderPage的返回值类型无法在JS赋值语句中被正确处理,因此抛出CS1963错误。
内容的提问来源于stack exchange,提问作者Jimmy C
相关产品推荐
相关产品推荐

