我正在尝试使用 html beginform 将 JS 变量发送到控制器操作。例如:
@using (Html.BeginForm("Index", "Contrl1", new { SPName = myJSVarcomeshere }, FormMethod.Post))
{
<button id="plot" type="submit" class="btn" > Plot </button>
}
目前的问题是 JS var 不在范围内。我可以使用隐藏字段来实现此目的吗
是的你是对的。写入表单的 @using 语句在服务器上执行 - Javascript 变量仅存在于客户端上。因此,您必须在表单内使用隐藏字段,并使用 javascript 变量的值填充该字段。您需要在文档加载后或隐藏字段下方的某个位置执行此操作。
Example:
@using (Html.BeginForm("Index", "Contrl1", FormMethod.Post))
{
<input type="hidden" name="SPName" id="SPName" />
<button id="plot" type="submit" class="btn" > Plot </button>
}
然后,使用JS填充隐藏字段:
jQuery 版本:
<script>
$(function(){
$('#SPName').val(myJSVarcomeshere);
});
</script>
普通 JS 版本:
<script>
window.onload = function() {
document.getElementById('SPName').value = myJSVarcomeshere;
};
</script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)