将jQuery值传递给MVC 3 Razor查看HTML Helper [英] Passing a jQuery value to MVC 3 Razor view html helper
问题描述
我在MVC Razor页面中嵌入了以下jQuery函数:
I have the following jQuery function embedded in an MVC Razor page:
<script type="text/javascript">
$(document).ready(function () {
$("input[name=MultiListsetting]").change(function () {
var valueString = "";
$("input[name=MultiListsetting]:checked").each(
function () {
valueString += this.id + ","
}
);
var MultiValueListResult = valueString.slice(0, -1);
alert(MultiValueListResult);
});
});
</script>
这将基于一系列复选框的id属性输出一个字符串.复选框值更改时,将重新构建字符串.因此,如果选中了3个复选框,则该函数将输出:"checkboxID1,checkboxID2,checkboxID3",直到更改为止.这是我们的数据库服务器存储这组复选框的值的方式.我现在需要完成的是将该函数输出的字符串传递到同一Razor页面上的隐藏HTML元素.
This outputs a string based on the id attribute of a series of checkboxes. When a checkbox value changes, the string gets rebuilt. So with 3 checkboxes, all checked, the function will output: "checkboxID1,checkboxID2,checkboxID3" until changed. This is the way our DB server stores values for this set of checkboxes. What I need to accomplish now is pass the string that this function outputs to a hidden HTML element on the same Razor page.
@Html.Hidden("SetViewModel[" + i + "].Value", [string output here])
jQuery会允许此举吗?我可以以某种方式将"MultiValueListResult"并将其放入隐藏的控件中吗?我还在研究.
Will jQuery allow this move? Can I somehow take "MultiValueListResult" and plop it into the hidden control? I'm still researching.
推荐答案
您在模板方法中混合了执行时间;您的HTML隐藏字段将在执行jQuery之前很久就出现在页面上.您需要做的就是简单地隐藏字段:
You're mixing execution time in your template methinks; your HTML hidden field will be on the page long before the jQuery is executed. What you need to do is simply make your hidden field:
@Html.HiddenFor(x => x.MyPropertyName);
然后在您的回调中,只需更新其值即可:
And then in your callback, simply update it's value:
$('#myElement').change(function()
{
$('#MyPropertName').val(MultiValueListResult);
});
当表单被发回时,所选集合的值将包含在隐藏值中.
When the form gets posted back, the value of your selected set will be contained within the hidden value.
这篇关于将jQuery值传递给MVC 3 Razor查看HTML Helper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!