Using ClientValidationFunction (JavaScript) in an UpdatePanel - c#

I'm trying to determine why my validation function is not being called on my web form. I've read through various articles at MSDN and most notably found this nugget.
When you use the CustomValidator control inside an UpdatePanel control,
make sure that the validator control and the control it is associated with
are in the same panel. For more information about using the UpdatePanel
control for partial-page updates, see Partial-Page Rendering Overview.
With this knowledge I modified my code as follows:
<asp:UpdatePanel ID="UpdatePanel0" runat="server">
<ContentTemplate>
<script type="text/javascript">
function IsNotChecked(obj, args) {
args.IsValid = false;
if (document.getElementByID("cbRegion0").checked)
{
args.IsValid = true; return true;
}
return false;
}
</script>
<asp:CheckBox ID="cbRegion0" runat="server" ValidationGroup="0" AutoPostBack="true" OnCheckedChanged="CheckBox_CheckedChanged" />
<asp:CustomValidator ID="CustomValidator0" runat="server" ValidationGroup="0" ClientValidationFunction="IsNotChecked" ErrorMessage="You did not check the box." ValidateEmptyText="True" />
</ContentTemplate>
</asp:UpdatePanel>
The issue I'm having is that the validation routine does not get executed when clicking the submit button on my page.
Some unique elements of the design is that the code above is actually inside of a .ascx that is added to the page via Control.Add() but I don't see how that would affect the ClientValidationFunction. I believe it's related to the placement of the <script> inside the form but despite following directions at MSDN it doesn't seem to have made a difference.
Thanks for any ideas!

Scripts inside of an UpdatePanel will be lost after an async postback. Try putting your IsNotChecked method outside of any update panels... or, implement IScriptControl and put your validation method in the client script file you create to accompany your script control...

I found the answer here at Stack Overflow in the How do I get Client-side validation of ASP.Net page to run? discussion. Sorry for not seeing this earlier. As #Brian pointed out, by specifying the ValidationGroup="0" in my code that it was expected that the submit button on the page have the same ValidationGroup assigned. In the end I just removed the attribute from the directive and it now calls the JS.
I found the answer because I was looking through the page source and noticed that the submit button was calling a javascript WebForm_OnSubmit() method which ultimately was checking Page_ValidationActive.
This led me to the question I've linked.
I hope this helps someone else.
Thanks!

Related

form.__EVENTTARGET.value undeffined in js

at my webforms.app on .net 4.0 after call _doPostBack via
aspx code
<%= GetPostBackReference() %>;
on code behind
protected string GetPostBackReference()
{
return Page.ClientScript.GetPostBackEventReference(ReloadThePanel,"null");
}
transformed to
__doPostBack('ctl00$cntMain$ReloadThePanel','null');
in form
<!-- update panel -->
<asp:UpdatePanel ID="updPanelSave" ClientIDMode="Static" runat="server">
<ContentTemplate></ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ReloadThePanel" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<!-- hidden button for update panel -->
<asp:LinkButton ID="ReloadThePanel" runat="server" style="display:none;" />
after first ajax postback is all ok, after another one ajax postback on same page it throw js exception
form.__EVENTTARGET.value undeffined
in (Scriptresource.axd ... dynamic code)
_doPostBack: function PageRequestManager$_doPostBack(eventTarget, eventArgument) ....
form.__EVENTTARGET.value = eventTarget;
form.__EVENTARGUMENT.value = eventArgument;
this._onFormSubmit();
what i do wrong ? Its maybee same isue with http://www.hanselman.com/blog/IE10AndIE11AndWindows81AndDoPostBack.aspx
problém is only on ie 11,8 usw.. Chrome and FF works well
Thanx
Easiest thing to do is upgrade to 4.5.1 - it may be that issue you mention and that'd solve it.
Seems strange that it happens AFTER and initial postback though (and doesn't tie in with the issue above).
Personally I don't see much point in creating the postback reference by using a hidden button (and suspect that's where it's getting itself confused). You have blank content template here, but there is probably something contained within in the real code, make sure you don't have any unmatched div tags as that would push the button into the panel and you'd lose reference to it.
I'm guessing that you must be calling the postback from javascript (otherwise why use a hidden button), so why not just use: . You might want to populate the id programatically (in aspx : ', '');"> )
I know it seems nasty including direct references to __dopostback - but the day M$ change that is the day that 90% of webforms websites will go down anyway, so it's pretty unlikely.

CodeMirror with UpdatePanel in asp.net

I'm using CodeMirror in an ASP.NET web application. The web app uses UpdatePanel (ajax).
In ajax postback, I'm not able to get updated text from the CodeMirror textbox on server side and after the postback, the text gets reset. This WORKS if I don't use an update panel. What am I missing?
Below is the code mirror code:
editor = CodeMirror.fromTextArea(document.getElementById("<%=txtLua.ClientID%>"), {
matchBrackets: true,
theme: "neat",
pollInterval: 100,
continuousScanning: 500
});
<asp:UpdatePanel ID="upd" runat="server">
<ContentTemplate>
<asp:TextBox runat="server" ID="txtLua" Height="320" Width="600" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" Text="btn" />
</ContentTemplate>
</asp:UpdatePanel>
Is there an asp.net/C# sample for using CodeMirror? Any help is appreciated.
The short answer is: create a javascript event hook that fires early (before the UpdatePanel begins to do its work) and manually calls CodeMirror's .save() function.
The problem seems to arise because the auto-magic form.submit override that CodeMirror supplies is triggered after the ScriptManager has already passed the ViewState of the panel back to the server. This means the server only receives the TextBox in its initial state (CodeMirror hasn't put what you've typed into it yet). I checked the DOM events in Chrome and ScriptManager's hook was consistently ahead of the form.submit override that CodeMirror added.
I got around this by adding an .onclick to the submit button right after CodeMirror loaded. Using your example:
var editor = CodeMirror.fromTextArea(document.getElementById("<%=txtLua.ClientID%>"), {
leaveSubmitMethodAlone: true, //since you don't need this anymore, no reason to complicate your DOM
matchBrackets: true,
theme: "neat",
pollInterval: 100,
continuousScanning: 500
});
window['cmLocalStateEvent'] = function () { editor.save(); };
//saveButton = document.getElementById("<%=btn.ClientID%>"); //grab the save button
//if (saveButton) {
// saveButton.onclick = function () { editor.save(); }; //make it do what the submit action was going to do
//}
<asp:UpdatePanel ID="upd" runat="server">
<ContentTemplate>
<asp:TextBox runat="server" ID="txtLua" Height="320" Width="600" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btn" runat="server" OnClientClick="if(window['cmLocalStateEvent'])window.cmLocalStateEvent();" OnClick="btn_Click" Text="btn" />
</ContentTemplate>
</asp:UpdatePanel>
Now the .onclick is ahead of the ScriptManager hook, and will fire first. Infact, if you put an OnTextChanged= and AutoPostBack= on the TextBox it'll fire even before the button that you just clicked does.
Essentially, the trick is to get CodeMirror's save to apply before ScriptManager submits the ViewState back to the server.
EDIT:
I've found since posting this, that you'll run into a troublesome issue if your submit button is also inside the UpdatePanel (which yours is). The .onclick will not persist after the initial submit and you'll be reset to a clean button with no event hooks. My current working solution to that scenario is adding a window['cmLocalSaveEvent'] function and adding the client .onclick to the ASP template (so the panel refresh puts it back for you). Updated code above to reflect this.
This is how I managed to make it work, just in case someone else needs it. After instantiating editor, I'm keeping the textbox aligned every time the blur event occurs.
editor.on('blur', function () {
arguments[0].save();
});

asp:button with no post back or refreshing the page

I have button in my page that when click on fires a jquery method that shows a div, but if the browser doesn't support javascript I want to fire a code behind method (using a postback). Is this possible? I'm already using this code but i can't see any results:
<asp:Button ID="Button1" runat="server" Text="Upload Files Here" Width="187px" onClick="CodeBehindMethod" OnClientClick="show_upload_box();return false"/>
and this is my jquery code:
function show_upload_box() {
$("#pop_up_background").css({
"opacity": "0.4"
});
$("#pop_up_background").fadeIn("slow");
$("#signup_pop_up_box").fadeIn('slow');
window.scroll(0, 0);
}
If the browser doesn't support JavaScript then your button would not work.
In ASP.NET, the runat="server" instruction is actually tied to a JavaScript method that submits a form (view page source to see that method).
Change or remove the value of that property to prevent the post back to your server.

Auto Fill Textbox in ASP.NET depending on the text typed in another textbox

how to fill textbox in asp.net while i am typing in another text
.. changes in one textbox will affect in another textbox auto.. and without refreshing my page.
Ok, try this. You will need the AJAX Control Toolkit. So read the article Installing AJAX Control Toolkit 4 in Visual Studio 2010 to see how to install it in Visual Studio.
Then you need to add a ScriptManager to your ASPX page. You will need to add the following code:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
What you then need to do, is add an UpdatePanel to your page. Inside this update panel, you need to place the textbox. This means that only the controls inside the update panel will refresh, and not the whole page. To do this, add the following code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!--Add your Textbox Control to update here: Textbox1-->
<asp:TextBox ID="Textbox1" runat="server" ReadOnly="True"></asp:TextBox>
<asp:TextBox ID="Textbox2" runat="server" ReadOnly="True" ontextchanged="Textbox2_TextChanged"></asp:TextBox>
</ContentTemplate>
<Triggers>
<!--This is the textbox you will be typing text into: TextBox2-->
<asp:AsyncPostBackTrigger ControlID="Textbox2" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
The Trigger tells your page which control on the form needs to initiate the postback. Now in your .cs file, you need to add the event handler for the Textbox2 TextChanged event. Add the following code:
protected void Textbox2_TextChanged(object sender, EventArgs e)
{
// Set the text of textbox1 = textbox2
}
I hope that this helps.
No need for AJAX. JQuery is enough. The code will do it
$('#text1').bind('keyup', function(){
$('#text2').val($('#text1').val());
});
Assuming
text1 id of box writing into.
text2 textbox that text gets copied to
in .Net you will have to use client id to get the correct id so it may look like this
$('<%=text1.ClientID%>').bind('keyup', function(){
$('<%=text2.ClientID%>').val($('#text1').val());
});
Oh and wrap it up in $(document).ready as per standard. And of coures you need to include the JQuery library to your page.
No posting back or page refreshes at all. It's your lightest solution and easy to implement.
You will need to use Javascript to accomplish this. ASP.Net code runs on the server side, which means it cannot affect the page without a postback happening first. Read up on the OnTextChanged event and how to hook into it with javascript. There is a javascript library called jQuery which makes everything easier, though it isn't strictly necessary.
Use JQuery. You may need to make an AJAX call to the server if you are relying on a datasource such as a database to autofil this field.

Showing errors in updatepanel after processing a CSV file

I have a csv importroutine which imports my CSV values into Sitecore. After this proces is done i want to show the errors in an asp:literal. This is not working, and I think this is because i need an updatepanel for this in order to be able to update text after the first postback (the csv upload / import).
I made this:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
and coded this:
string melding = string.Format("Er zijn {0} objecten geïmporteerd.{1}", nrOfItemsImported, errors);
ViewState["Melding"] = melding;
And i have a button. On the onclick of this button I have:
Literal literal = new Literal();
literal.Text = (string)ViewState["Melding"];
literal.ID = DateTime.Now.Ticks.ToString();
UpdatePanel1.ContentTemplateContainer.Controls.Add(literal);
PlaceHolder1.Controls.Add(literal);
When i now press the button i want to update the panel so that it will show my Literal with the errormsg on it. This however isn't happening. How can this be? I'm guessing it has something to do with my viewstate, i don't see keys on the viewstate after I press the button...
#Update:
I found the problem. I was storing information in a session, however the data for the key i was storing the information in was too large. This made the Session key empty. I was posting an empty string into my literal and therefore no information was shown. I am now looking for a better way to store my data and make it show in my updatepanel. I have tried Viewstate / Session / Cookies and none of it would work the way i wanted. When I am using a viewstate I am not able to store information. The viewstate (debugmode) shows count 0 and 0 keys ... Hope someone knows a good way to make sure that my errorstring (476kb) gets stored somewhere where i can easily post it to my updatepanel's literal.
If you are using a FileUpload control, then you cannot use the UpdatePanel to asynchronously update the panel. The file upload is a synchronous event, so you'll need to update the Literal control on the page after the upload completed during the next Page_Load event.
In your code, have you tried UpdatePanel1.Update();? Even though you have added a control, you still will need to "trigger" the update to the update panel.
See here for a possible similar issue: StackOverflow
I tried this code and on click of button I am able to get the literal text on web page. Can you provide with some more details .

Categories