Passing a jQuery value to MVC 3 Razor view html he

2019-07-28 02:21发布

问题:

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>

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])

Will jQuery allow this move? Can I somehow take "MultiValueListResult" and plop it into the hidden control? I'm still researching.

回答1:

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.