如何在MVC3中的Html beginform中发送javascript var [英] How to send javascript var in Html beginform in MVC3

查看:61
本文介绍了如何在MVC3中的Html beginform中发送javascript var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用html beginform将JS变量发送到控制器操作。例如:

I am trying to send a JS variable using html beginform to controller action. Eg:

@using (Html.BeginForm("Index", "Contrl1", new { SPName = myJSVarcomeshere }, FormMethod.Post))
{ 
    <button id="plot" type="submit" class="btn" > Plot </button>
}

目前问题是JS var不在范围内。我可以使用隐藏字段来实现此目的

Currently the problem is the JS var is not in scope. Can I use a hidden field to achieve this

推荐答案

是的,你是对的。编写我们表单的@using语句在服务器上执行--Javascript变量仅存在于客户端上。因此,您必须在表单内使用隐藏字段,并使用javascript变量的值填充该字段。您需要在文档加载后或隐藏字段下方的某个位置执行此操作。

Yes you are right. The @using statement which writes our your form is executed on the server - the Javascript variable is only present on the client. Therefore you will have to use a hidden field inside the form and populate that field with the value of your javascript variable. You need to do that once the document has loaded or somewhere below the hidden field.

示例:

@using (Html.BeginForm("Index", "Contrl1", FormMethod.Post))
{ 
    <input type="hidden" name="SPName" id="SPName" />
    <button id="plot" type="submit" class="btn" > Plot </button>
}

然后,使用JS填充隐藏字段:

Then, use JS to populate the hidden field:

JQuery版本:

<script>
$(function(){
$('#SPName').val(myJSVarcomeshere);
});
</script>

普通JS版本:

<script>
window.onload = function() {
document.getElementById('SPName').value = myJSVarcomeshere;
};
</script>

这篇关于如何在MVC3中的Html beginform中发送javascript var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆