如何在MVC3中使用Html.BeginForm发送JavaScript变量

3
我正在尝试使用html beginform将JS变量发送到控制器操作。例如:
@using (Html.BeginForm("Index", "Contrl1", new { SPName = myJSVarcomeshere }, FormMethod.Post))
{ 
    <button id="plot" type="submit" class="btn" > Plot </button>
}

目前的问题是JS变量不在作用域内。我可以使用隐藏字段来解决这个问题。

1个回答

7

是的,你说得对。@using语句用于编写表单时在服务器上执行,而Javascript变量仅存在于客户端。因此,您需要在表单中使用隐藏字段,并使用Javascript变量的值填充该字段。您需要在文档加载后或隐藏字段下方执行此操作。

示例:

@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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接