输入隐藏控件不会在回发之间保持其值

时间:2010-11-25 17:17:21

标签: javascript asp.net html asp.net-mvc hidden-field

我正在使用ASP.NET MVC创建一个网页。 我有以下输入隐藏的定义:

<%=Html.Hidden("inputHiddenSelectedMenuId") %>

我在这个js函数中设置了它的值:

function SetSelectedMenu(id) {
     $('#inputHiddenSelectedMenuId').val(id);         
 }

在js init函数中进行回发后,我想使用隐藏输入中设置的值,但值为字符串为空。

$(document).ready(function() {

     $('div.nav > a').removeClass('active');
     var id = $('#inputHiddenSelectedMenuId').val();
     if (id != "") {
         $("#" + id).addClass('active');
     }         
 });

任何人都可以暗示为什么会这样吗?

1 个答案:

答案 0 :(得分:2)

您正在尝试在javascript中读取输入的值。当您单击表单上的按钮并执行回发操作时,您的页面将被重新加载,并且每次加载页面时都会重新运行javascript。如果你所做的只是在javascript中读取输入的值,则不需要执行回发。

$('#inputHiddenSelectedMenuId').bind('click', function ()
{
     var id = $('#inputHiddenSelectedMenuId').val();
     // do stuff with it.
});

点击功能将在没有回发的情况下执行。

现在,如果您尝试在帖子后从MVC中读取隐藏字段的内容,那么这是一个不同的问题。您必须通过模型绑定从表单数据中提取它(或直接通过Request.Form []集合读取它。

public ActionResult SomeActionToPostTo(int inputHiddenSelectedMenuId)
{
     //model binding should find the form field called inputHiddenSelectedMenuId and populate the argument in this method with it's value. If it's not an integer then just change the type of the argument to the appropriate type.
}