3

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

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

1 Answer 1

7

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.

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(myJSVarcomeshere);
});
</script>

Plain JS version:

<script>
window.onload = function() {
document.getElementById('SPName').value = myJSVarcomeshere;
};
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.