1

我正在使用 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');
     }         
 });

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

4

1 回答 1

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.
}
于 2010-11-25T17:40:01.890 回答