开发者

Input hidden control doesn´t keep the his value between postbacks

I'm making an webpage using ASP.NET MVC. I have the following input hidden definied:

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

And i set its value in this js function:

function SetS开发者_运维百科electedMenu(id) {
     $('#inputHiddenSelectedMenuId').val(id);         
 }

After a make a postback in the js init function i want to use the value set in the input hidden but the value is string empty.

$(document).ready(function() {

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

Can anyone give a hint why this is happening?


You are trying to read the value of the input in javascript. When you click a button on a form and it does a post back your page is being reloaded and the javascript re-runs every time the page is loaded. If all you are doing is reading the value of an input in javascript you do not need to perform a postback.

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

The click function will be performed without a postback.

Now, if you are trying to read the contents of the hidden field from within MVC after a post then this is a different issue. You will have to pull it from the form data through model binding (or reading it directly through the Request.Form[] collection.

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.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜