在javascript函数中设置razor @ Html.Hidden

时间:2012-07-25 10:22:45

标签: c# javascript razor hidden

有没有办法在JavaScript代码块中设置razor @HTML.Hidden控件值?

<tbody>

                    @Html.Hidden("customerID")
                    @if (Model != null)
                    {
                        var customers = Model.Customers.ToList();
                        for (var i = 0; i < customers.Count; i++)
                        {
                        <tr class="gradeX">
                            <td>
                                <a href="#"><span onclick="GetCustomerID()">@customers[i].CustomerId.ToString()</span></a>
                            </td>
                            <td>
                                <a href="#">@customers[i].Name</a>
                            </td>                                
                        </tr>
                        }
                    }
                </tbody>

我的JavaScript块是

<script type="text/javascript">
    var globleCustomerId = null;

    function GetCustomerID() {

        globleCustomerId = $('#customerID').val();

        //globleCustomerId value should be set to @Html.Hidden()


    }
</script>

在这个JavaScript块中,我需要将globleCustomerId值设置为@ Html.Hidden(“customerID”)。

如何获得该值?

3 个答案:

答案 0 :(得分:2)

您可以使用.val()方法:

$('#customerID').val('some value');

有两个重载:一个不带任何参数,允许你读取值(以及你在问题中显示的那个)和一个带参数并设置值的重载(一个我在答案中表明了。


更新:

显然,您正在尝试将隐藏字段中所点击的客户ID的值。在这种情况下,您可以简单地为span元素提供一个类:

<a href="#">
    <span class="customerId">
        @customers[i].CustomerId.ToString()
    </span>
</a>

然后只需订阅此元素的click事件:

$(function() {
    $('.customerId').click(function() {
        $('#customerId').val($(this).text());
        return false;
    });
});

答案 1 :(得分:2)

function GetCustomerID() {

    globleCustomerId = $('#customerID').val();

     //  Use this line to set the globleCustomerId value to @Html.Hidden() field

      $('#customerID').val(globleCustomerId);

}

答案 2 :(得分:1)

纯粹的Javascript版本是;

//set
document.getElementById("customerID").value = "new value";
//get
var customerIDValue = document.getElementById("customerID").value;