Refresh issue in ASP.Net MVC4 view - asp.net

I have code like below in ASP.Net MVC4. and I am using Razor engine.
#{
string sDefaultEnvironId = string.Empty;
}
<script language="javascript" type="text/javascript" >
function changeHd() {
$("#hdSelEnvironmentId").val("1");
}
</script>
<input type="button" value="ChangeHD" onclick="changeHd();" />
#Html.Hidden("hdSelEnvironmentId", sDefaultEnvironId)
The value of hidden field hdSelEnvironmentId is empty when accessing this view at first time. then it was changed to 1 after I clicked button ChangeHD.
But after I pressed F5, the value of hidden field hdSelEnvironmentId is still 1, I expected it with initial empty value instead of 1. Can anyone help me to figure it out ?I just can not understand it. I am using Firefox and Firebug, thanks.

Edit As discovered by Andreas here, you can remove this behavior by adding an attribute autocomplete=off to your input:
#Html.Hidden("hdSelEnvironmentId", sDefaultEnvironId, new { autocomplete = "off" })
This effect is not due to the cache -- it's a feature (bug?) of Firefox, that when you refresh a page, the inputs of the page do not seem to get re-loaded from the server.
try the same thing in Chrome or IE, you'll see that the value resets to empty
clear the cache in Firefox, and you'll notice the value still does not get reset.
So, I'm not sure if there's a workaround, but this issue does seem to be restricted to Firefox.

instead of setting it in
#{
string sDefaultEnvironId = string.Empty;
}
just initialize it in JavaScript.
$(document).ready(function(){
$("#hdSelEnvironmentId").val() = "";
});
function changeHd() {
$("#hdSelEnvironmentId").val() = "";
$("#hdSelEnvironmentId").val("1");
}
i think this will help.. even on page refresh as document loads again the value will be set to empty and then to 1 on button click

Related

The jquery keyup event is not working

I am working on making a Sharepoint 2007 app look more modern. I am using jQuery actively for that and even though I am no expert, I have learnt enough to know my ways around. Untill I faced this issue today. Here are the bits:
$(document).ready(function() {
alert('doc ready');
var textBox1 = $("#myTest");
alert(textBox1);
textBox1.keyup(function() {
alert('key UP');
});
textBox1.live("keyup", function() {
alert('keykeykey up live');
});
});
Server-generated html:
<input name="ctl00$Spwebpartmanager1$g_1f2d211c_a0c3_490d_8890_028afd098cac$ctl00$myTest" type="password" id="ctl00_Spwebpartmanager1_g_1f2d211c_a0c3_490d_8890_028afd098cac_ctl00_myTest" class="gh" />
So the document ready handler fires, the textbox1 variable is not null, but none of the eventhandlers to handle the keyup event ever fire? The mind reels...
I doesn't work because the id attribute is actaully ctl00_Spwebpartmanager1_g_1f2d211c_a0c3_490d_8890_028afd098cac_ctl00_myTest
try
var textBox1 = $("input[id$='_myTest']");
Here were looking for a html input field with has an id attribute that ends with the string _myTest
In future for your debugging use
alert(textBox1.length)
So that you can whether the jQuery object is empty or not. If the selector doesn't find anything it will return an empty jQuery object which isn't null. You can test for whether the selector found anything by making sure that the .length property is positive.

Whats the difference if I set hidden field value through html anchor OR asp.net linkbutton?

The problem is, I have a set of links onclick of those links I am setting the linkId into a Hidden field. First my link were asp:linkbutton ans onClientClick I was setting the hiddenfield value.that time I was able to get the hidden field value from code behind but when I changed my links to HTML anchor and onClick I set the hidden field value , I am not getting hidden field with blank. when I debug JavaScript it is perfectly setting the hidden field value but why I am not getting it in code behind---my code-
<a href="./ContentPage.aspx" data-flexmenu='flexmenu1' onclick="javascript:setPageLinkId(1);">
<script type="text/javascript">
function setPageLinkId(lnkPageId) {
debugger;
alert(lnkPageId);
document.getElementById('<%=hdnSelectedLink.ClientID %>').value = lnkPageId.toString();
}
</script>
//code behind- here I get blank hidden field
if (hdnSelectedLink.Value != null && hdnSelectedLink.Value != "")
{
GetLinkPage(Convert.ToInt32(hdnSelectedLink.Value));
}
Whats the problem ,Please suggest?
My theory is that the click on the anchor doesn't cause a postback to the page. Rather a HTTP GET Request to "ContentPage.aspx" is issued, meaning that any form values are not posted to the server.
You need to use a control that causes a postback to the page...for example ASP:LinkButton as you had before.
#Ozzy you were right dude.I used this in my javascript-
document.forms["aspnetForm"].submit();
its working fine now.

ASP.NET postbacks lose the hash in the URL

On an ASP.NET page with a tabstrip, I'm using the hash code in the URL to keep track of what tab I'm on (using the BBQ jQuery plugin). For example:
http://mysite.com/foo/home#tab=budget
Unfortunately, I've just realized that there are a couple of places on the page where I'm using an old-fashioned ASP.NET postback to do stuff, and when the postback is complete, the hash is gone:
http://mysite.com/foo/home
... so I'm whisked away to a different tab. No good.
This is a webforms site (not MVC) using .NET 4.0. As you can see, though, I am using URL routing.
Is there a way to tell ASP.NET to keep the hash in the URL following a postback?
The problem is that the postback goes to the url of the current page, which is set in the action of the form on the page. By default this url is without #hash in asp.net, and its automatically set by asp.net, you have no control over it.
You could add the #hash to the forms action attribute with javascript:
document.getElementById("aspnetForm").action += location.hash
or, if updating an action with a hash already in it:
var form = document.getElementById("aspnetForm");
form.action = form.action.split('#')[0] + location.hash
just make sure you execute this code on window.load and you target the right ID
I tried to put the code from Willem's answer into a JS function that got called everytime a new tab was activated. This didn't work because it kept appending an additional #hash part to the URL every time I switched tabs.
My URL ended up looking like http://myurl.example.com/home#tab1#tab2#tab3#tab2 (etc.)
I modified the code slightly to remove any existing #hash component from the URL in the <form> element's action attribute, before appending on the new one. It also uses jQuery to find the element.
$('.nav-tabs a').on('shown', function (e) {
// ensure the browser URL properly reflects the active Tab
window.location.hash = e.target.hash;
// ensure ASP.NET postback comes back to correct tab
var aspnetForm = $('#aspnetForm')[0];
if (aspnetForm.action.indexOf('#') >= 0) {
aspnetForm.action = aspnetForm.action.substr(0, aspnetForm.action.indexOf('#'));
}
aspnetForm.action += e.target.hash;
});
Hope this helps someone!
I have another solution, implemented and tested with chrome, IE and safari.
I am using the "localStorage" object and it suppose to work all the browsers which support localStorage.
On the click event of tab, I am storing the currentTab value to local storage.
$(document).ready(function() {
jQuery('.ctabs .ctab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
localStorage["currentTab"] = currentAttrValue;
// Show/Hide Tabs
jQuery('.ctabs ' + currentAttrValue).show().siblings().hide();
// Change/remove current tab to active
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
if (localStorage["currentTab"]) {
// Show/Hide Tabs
jQuery('.ctabs ' + localStorage["currentTab"]).show().siblings().hide();
// Change/remove current tab to active
jQuery('.ctabs .ctab-links a[href$="' + localStorage["currentTab"] + '"]').parent('li').addClass('active').siblings().removeClass('active');
}
});

jQuery Autocomplete losing text on AutoPostBack

I have a jQuery Autocomplete field on an ASP.Net Webform and everything has been working great until now. I also have a DropDownList that I have a need to fire onSelectedIndexChanged with AutoPostBack.
When I changed my code to do the AutoPostBack, the text field that has the jQuery AutoComplete on it comes back blank. However, if I look at the source of the page, the text is in the text field. If I now post the form, the page will send back a blank field. My Google-Fu is weak on this one, as I could not come up with any workaround for it.
Has anyone had any issues like this with the Autocomplete field getting blanked out on an AutoPostBack, and how did you get around it?
I can post code if it's really necessary, but I'd need to sanitize a lot of it before I could due to company policy.
How is the autocomplete field being initialized? Is it being set to empty string either on page load from server or by the autocomplete jQuery plugin on document.ready?
If the source code for the plug-in is setting the textbox to empty string on document.ready then try the following:
// Store current textbox value in a var
var temp = $('#mytextbox').val();
// Initialize the autocomplete plugin (winging it on the syntax)
$('#mytextbox').autocomplete();
// Reset the value of the textbox.
$('#mytextbox').val(temp);
If you use jQuery Autocomplete plugin 1.1,
* Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
Add "autoPostBackSelection: false," in the options Ex:
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
autoPostBackSelection: false,
...
After, add this just before the "return true; at the end of the "selectCurrent() function.
if (options.autoPostBackSelection == true) {
__doPostBack($input.id, "");
}
Example:
function selectCurrent() {
...
if (options.autoPostBackSelection ==
true) {
__doPostBack($input.id, "");
}
return true;
}

Programmatically triggering events in Javascript for IE using jQuery

When an Event is triggered by a user in IE, it is set to the window.event object. The only way to see what triggered the event is by accessing the window.event object (as far as I know)
This causes a problem in ASP.NET validators if an event is triggered programmatically, like when triggering an event through jQuery. In this case, the window.event object stores the last user-triggered event.
When the onchange event is fired programmatically for a text box that has an ASP.NET validator attached to it, the validation breaks because it is looking at the element that fired last event, which is not the element the validator is for.
Does anyone know a way around this? It seems like a problem that is solvable, but from looking online, most people just find ways to ignore the problem instead of solving it.
To explain what I'm doing specifically:
I'm using a jQuery time picker plugin on a text box that also has 2 ASP.NET validators associated with it. When the time is changed, I'm using an update panel to post back to the server to do some things dynamically, so I need the onchange event to fire in order to trigger the postback for that text box.
The jQuery time picker operates by creating a hidden unordered list that is made visible when the text box is clicked. When one of the list items is clicked, the "change" event is fired programmatically for the text box through jQuery's change() method.
Because the trigger for the event was a list item, IE sees the list item as the source of the event, not the text box, like it should.
I'm not too concerned with this ASP.NET validator working as soon as the text box is changed, I just need the "change" event to be processed so my postback event is called for the text box. The problem is that the validator throws an exception in IE which stops any event from being triggered.
Firefox (and I assume other browsers) don't have this issue. Only IE due to the different event model. Has anyone encountered this and seen how to fix it?
I've found this problem reported several other places, but they offer no solutions:
jQuery's forum, with the jQuery UI Datepicker and an ASP.NET Validator
ASP.NET forums, bug with ValidatorOnChange() function
I had the same problem. Solved by using this function:
jQuery.fn.extend({
fire: function(evttype){
el = this.get(0);
if (document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(evttype, false, false);
el.dispatchEvent(evt);
} else if (document.createEventObject) {
el.fireEvent('on' + evttype);
}
return this;
}
});
So my "onSelect" event handler to datepicker looks like:
if ($.browser.msie) {
datepickerOptions = $.extend(datepickerOptions, {
onSelect: function(){
$(this).fire("change").blur();
}
});
}
I solved the issue with a patch:
window.ValidatorHookupEvent = function(control, eventType, body) {
$(control).bind(eventType.slice(2), new Function("event", body));
};
Update: I've submitted the issue to MS (link).
From what you're describing, this problem is likely a result of the unique event bubbling model that IE uses for JS.
My only real answer is to ditch the ASP.NET validators and use a jQuery form validation plugin instead. Then your textbox can just be a regular ASP Webforms control and when the contents change and a postback occures all is good. In addition you keep more client-side concerns seperated from the server code.
I've never had much luck mixing Webform Client controls (like the Form Validation controls) with external JS libraries like jQuery. I've found the better route is just to go with one or the other, but not to mix and match.
Not the answer you're probably looking for.
If you want to go with a jQuery form validation plugin concider this one jQuery Form Validation
Consider setting the hidden field _EVENTTARGET value before initiating the event with javascript. You'll need to set it to the server side id (replace underscore with $ in the client id) for the server to understand it. I do this on button clicks that I simulate so that the server side can determine which OnClick method to fire when the result gets posted back -- Ajax or not, doesn't really matter.
This is an endemic problem with jQuery datepickers and ASP validation controls.
As you are saying, the wrong element cross-triggers an ASP NET javascript validation routine, and then the M$ code throws an error because the triggering element in the routine is undefined.
I solved this one differently from anyone else I have seen - by deciding that M$ should have written their code more robustly, and hence redeclaring some of the M$ validator code to cope with the undefined element. Everything else I have seen is essentially a workaround on the jQuery side, and cuts possible functionality out (eg. using the click event instead of change).
The bit that fails is
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
which throws an error when it tries to get a length for the undefined 'vals'.
I just added
if (vals) {
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
and she's good to go. Final code, which redeclares the entire offending function, is below. I put it as a script include at the bottom of my master page or page.
Yes, this does break upwards compatibility if M$ decide to change their validator code in the future. But one would hope they'll fix it and then we can get rid of this patch altogether.
// Fix issue with datepicker and ASPNET validators: redeclare MS validator code with fix
function ValidatorOnChange(event) {
if (!event) {
event = window.event;
}
Page_InvalidControlToBeFocused = null;
var targetedControl;
if ((typeof (event.srcElement) != "undefined") && (event.srcElement != null)) {
targetedControl = event.srcElement;
}
else {
targetedControl = event.target;
}
var vals;
if (typeof (targetedControl.Validators) != "undefined") {
vals = targetedControl.Validators;
}
else {
if (targetedControl.tagName.toLowerCase() == "label") {
targetedControl = document.getElementById(targetedControl.htmlFor);
vals = targetedControl.Validators;
}
}
var i;
if (vals) {
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
ValidatorUpdateIsValid();
}
This is how I solved a simlar issue.
Wrote an onSelect() handler for the datepicker.
link text
In that function, called __doPostBack('textboxcontrolid','').
This triggered a partial postback for the textbox to the server, which called the validators in turn.

Resources