最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to send javascript var in Html beginform in MVC3 - Stack Overflow

programmeradmin7浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 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(myJSVareshere);
});
</script>

Plain JS version:

<script>
window.onload = function() {
document.getElementById('SPName').value = myJSVareshere;
};
</script>
发布评论

评论列表(0)

  1. 暂无评论