I am trying to send a JS variable using html beginform to controller action. Eg:
@using (Html.BeginForm("Index", "Contrl1", new { SPName = myJSVareshere }, FormMethod.Post))
{
<button id="plot" type="submit" class="btn" > Plot </button>
}
Currently the problem is the JS var is not in scope. Can I use a hidden field to achieve this
I am trying to send a JS variable using html beginform to controller action. Eg:
@using (Html.BeginForm("Index", "Contrl1", new { SPName = myJSVareshere }, FormMethod.Post))
{
<button id="plot" type="submit" class="btn" > Plot </button>
}
Currently the problem is the JS var is not in scope. Can I use a hidden field to achieve this
Share Improve this question asked Jun 30, 2014 at 11:14 user2906420user2906420 1,2696 gold badges31 silver badges44 bronze badges1 Answer
Reset to default 7Yes 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.
Example:
@using (Html.BeginForm("Index", "Contrl1", FormMethod.Post))
{
<input type="hidden" name="SPName" id="SPName" />
<button id="plot" type="submit" class="btn" > Plot </button>
}
Then, use JS to populate the hidden field:
JQuery version:
<script>
$(function(){
$('#SPName').val(myJSVareshere);
});
</script>
Plain JS version:
<script>
window.onload = function() {
document.getElementById('SPName').value = myJSVareshere;
};
</script>