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

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 SetSelectedMenu(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.
}

Related

assigning value to hidden field from javascript

I am trying to do what seems to be simple but am unable to accomplish
I am trying to set the value of a column after a row focus change in a grid to a hidden value in java script.
My imbedded javascript code:
function OnGridFocusedRowChanged() {
grdA.GetRowValues(grdA.GetFocusedRowIndex(), 'ClientID', OnGetRowValues);
}
function OnGetRowValues(values) {
//Set hidden value
document.getElementById('<%=hdnClientID.ClientID%>').value = values[0];
//Fire button click
btnPopulateGrids_Click();
}
where hdnClientID is the name of my hidden field
In GridA I have the setting as such that OnGridFocusedRowChanged gets executed each time a row focus change takes place.
To this point, it works fine, the values[0] in OnGetRowValues() contains the correct value from the corresponding row in GridA.
But in the corresponding code behind, I cannot access the value from hidden field hdnClientID. Always comes up null when accessing
Current_Client_ID = CInt(hdnClientID.Value);
cannot access or convert any value from
hdnClientID.ClientID.
either.
I'm missing something simple.
I had to complete a similar task recently and I too was unable to access the value from codebehind. I researched and found out that it is not that simple and that you can't do it with javascript. What I would recommend is to check if you have jQuery installed and if you do, change your function to this:
function OnGetRowValues(values) {
//Set hidden value
$('#<%=hdnClientID.ClientID%>').val(values[0]);
//Fire button click
btnPopulateGrids_Click();
//If you change your HiddenField to have OnValueChange event, you can trigger it with this
//__doPostBack('<%= CompanyCode.ClientID %>', '');
}
Also, I guess you are firing some function from code behind with btnPopulateGrids_Click();.
I would recommend adding OnValueChanged="hdnClientID_OnValueChanged"/> to your <asp:HiddenField/> and using my supplied function triggering method.

access local storge with javascript and C#, asp.net

i am hoping someone will help me, i am pulling out my hair for the last few hours...!
I am using asp.net web forms with c#
I have the following button in my menu , this button opens up a page that lists selected properties for realtor…
htmlCode.Append("<button type='button' class='btn btn-basic' id='btnEnquire' onclick='openEnquiryPage()'> <span class='glyphicon glyphicon-th-list'></span> View my list </button>");
function openEnquiryPage() {
location.href = "EnquiryPage.aspx";
//get the list from the storage into the hidden field
//getListOfProperties();//not in use...
}
The list is stored in localstorage as Json, I can see the correct data in the text box on the page
var retrievedData = localStorage.getItem("propertyArray");
proplist2.value = retrievedData;
declared as follows in asp.net control
<asp:TextBox ID="TextBox1" runat="server" Text="initial"></asp:TextBox>
BUT in the hidden field, the data is always = ""
<asp:HiddenField ID="txtPropList" runat="server"></asp:HiddenField>
javascript to populate the hidden field...
function getListOfProperties() {
document.getElementById("body_content_txtPropList").value = retrievedData;
var proplist2 = document.getElementById("body_content_txtPropertyList");
proplist2.value = retrievedData;
}
when I debug the following lines in the code behind ...
Page.ClientScript.RegisterStartupScript(this.GetType(),"prop", "getListOfProperties();",true);
_propertyListJson = txtPropList.Value;
propertyListJson I always = “”
Thank-you in advance.!
If you want to use the hidden field then you should use
<%=txtPropList.ClientID%>
as on when you render the page and see it in inspect element server would render the different Id so it would not store the value in hidden field simply so it is feasible to use ClientID to create the static mode. But as on when you call the javascript function from the c# code then it would call the javascript function but it would not wait for it and execute the next line of code as on at that time the value is not store in hidden field so it would return the null value.
If you want then call the function of javascript on page load event and then click the button and retrieve the value it would successfully retrieve the value but i dont think that these would be the feasible code from my opinion
I suggest to create the WebAPI which would simply get the the data from the localstorage and perform the operation
And webAPI can be easily called from javascript using ajax call
I hope this would be helpful and answer is satisfactory 😊☺
Thank You ☺🙂

Javascript value to hidden field

I have a function that sets a date on change to a hidden field. I am currently receiving and populating a field with a date from the server. When i submit the field without a change it is returning as an empty string even though it does originally display a date. How can i make sure that the displayed date gets saved back to server if no change is made?
$(":asp(LeadEffectiveDate)").change(function () {
var effectiveDate = $(":asp(LeadEffectiveDate)").val();
$(":asp(LeadEffectiveDateToSetForUserRole)").val(effectiveDate);
});
If your date is already being populated inside a page load function add the
there.
$(":asp(LeadEffectiveDateToSetForUserRole)").val(effectiveDate)
Read it on the document ready event. Update it when the dropdown changes.
$(function(){
var effectiveDate = $(":asp(LeadEffectiveDate)").val();
$(":asp(LeadEffectiveDateToSetForUserRole)").val(effectiveDate);
$(":asp(LeadEffectiveDate)").change(function () {
effectiveDate = $(":asp(LeadEffectiveDate)").val();
$(":asp(LeadEffectiveDateToSetForUserRole)").val(effectiveDate);
});
});
On a side note, I personally prefer to do my jQuery selectors with an Id attribute ($("#SomeUniqueId")).

After AJAX callback, onblur goes back to original (or updated) field

I have an AJAX callback:
HTML:
<a onCLick="loadXMLDoc(id1,id2)">(Add)</a>
This calls an AJAX function that calls back a basic html input field in place of the above "(Add)"
onChange in this input field performs another AJAX callback that loads user input into a database.
What I am trying to do is once the field is filled out (or not filled out) and the field is blurred, it either goes back to the original or the newly updated value (but not any longer an input field).
I have searched around for a while and have come up with nothing. I am also new to javascript and AJAX. If it helps, I am using PHP mainly in this application.
Thanks
ADDITION
This is what I am trying to achieve:
The page lists different entries in table format.
There is a specific field that either has an id (stored in the database), or if field is null (in database) that field will display a button to add the id.
When pressed, the button calls a function which calls back an input field, the this replaces the previous "add" button. The AJAX callback places the input field in place of the "add" button.
This is where I need the help: After the user inputs the ID (or decides not to) and once the field no longer has focus, it changes from an input field back to what it was or the newly enter id. I am trying to do all this without refreshing the page.
I still don't follow exactly, but hopefully this will show you a means of creating/changing DOM elements in response to events like you've mentioned:
$(document).ready(function() {
$("#container").on("blur", ".name", function(e) {
var val = $(this).val();
if (!val) {
$(this).closest(".row").html("<button class='add'>Add</button>");
} else {
$(this).closest(".row").html("<span class='label'>Name: </span><span>" + val + "</span>");
}
});
$("#container").on("click", ".add", function(e) {
var html = "<span class='label'>New Name: </span><input class='name' type='text' />";
var row = $(this).closest(".row").html(html);
row.find("input").focus();
});
});
Working demo: http://jsfiddle.net/jfriend00/01ajd0y9/

Client side javaScript to toggle a dropdownlists effects reversed on postbacks?

I have the following JavaScript to toggle a dropdownlists in a ASP.NET page, which gets called when I click a button. I have like 4-5 dropdownlist/Toggle button pairs. Each toggle button toggles the enable/disable property on the associated dropdownlist.
function toggleDisableDropDown(dropDownID) {
var element = document.getElementById(dropDownID); // get the DOM element
if (element) { // element found
element.disabled = !element.disabled; // invert the boolean attribute
}
return false; // prevent default action
}
But one of my dropdownlist needs to do a postback everytime. I pick an item to populate another dropdownlist, what I noticed is that on this postback all of my other dropdownlist which were disabled by javascript (user clicks on the toggle button for these dropdownlist) gets enabled.
What is happening here? And how can I fix it?
Javascript DOM manipulation has no relevance to the control's saved state on the server. Changing the enabled property on the dropdownlists on the client side will not be known to the control state on the server.
Posting back re-creates the dropdownlist's using the last known state of the control. If you want to have them re-rendered using the last state on the client, you'll need to post some client tracking information as well. You could track each dropdownlist's client state in a hidden field, and use the posted value from those hidden fields to update the Enabled property of the dropdownlist on the server.
//Html
<input type="hidden" name="_trackingDropdown1" value="true" />
//Client Javascript
function toggleDisableDropDown(dropDownID) {
var element = document.getElementById(dropDownID); // get the DOM element
var trackingField = document.getElementById("_tracking" + dropDownID);
if (element) { // element found
element.disabled = !element.disabled; // invert the boolean attribute
trackingField.value = element.disabled;
}
return false; // prevent default action
}
//On Server during postback handling
if (Request.Params["_trackingDropDown1"] != null)
{
bool.TryParse(Request.Params["_trackingDropDown1"], out DropDownList1.Enabled);
}

Categories