How to validate server side code in Javascript - c#

I am getting some value from server , if the value is false i need to show alert message on UI without refreshing or postbacking the page.
What i am doing currently is i get the value from server i declare one hidden control and store that value in hidden control and in aspx page i write one JS method to check if that value is false show the alert message, but the problem is i have to do this on click on a button which is present in code behind
so as soon as i click on that button JS code gets executed before i get value from server.
function fnvalidation() {
if (document.getElementById("<%=hdnCtrl.ClientID%>").value == false) {
alert('Please submit it again');
return false;
}
}
On page load i am registering like this :
btnSave.Attributes.Add("onclick", "return fnvalidation()");
C# Code :
bValidate = CommonUtility.ValidateOutput();
hdnCtrl.Value = bValidate.ToString();//Storing value in hidden variable
if(bvalidate == false)
{
//Call javascript method fnvalidation
}
How to call this JS method correctly when value is false coming from server ?
Thanks.

If your page needs to fetch data from the server without refreshing the page, then you need to use AJAX. Which comes down to two things:
Create an AJAX endpoint in server-side code.
Consume that AJAX endpoint from client-side code.
The server-side code likely has several options. HTTP Handlers, empty ASPX pages which clear and response and set a new content type, maybe even Web Methods? It's been a long time since I've used WebForms, so I'm not 100% sure what the recommended approach is right now. But I think Web Methods are what you're looking for. So your code-behind would have something like this:
public partial class MyPage : Page
{
[WebMethod]
public static string GetValue()
{
return "some value";
}
}
Then, assuming you're using jQuery for example, you would call that endpoint from your client-side code:
$.ajax({
type: "POST",
url: "MyPage.aspx/GetValue"
}).done(function (data) {
// respond to the value in "data"
}).error(function () {
// there was an error
});
Now your client-side button click handler can use that, or something like it, to fetch the value from the server. If that's all that button needs to do then don't make it an asp:Button but instead just an input type="button" so that it doesn't post back the whole page. Keeping it as a server-side button would mean canceling the event propagation in JavaScript, which gets ugly with asynchronous operations because there's no immediate way to resume event propagation, you'd have to manually invoke the post back.

I think you can use
Page.ClientScript.RegisterStartupScript
inside your condition if(bvalidate == false) condition like then no need to rely on the value to be set ( i.e in java script function you can remove checking the hidden field value simply alert the user.
Also you can remove this code btnSave.Attributes.Add("onclick", "return fnvalidation()")
Page.ClientScript.RegisterStartupScript(this.GetType(), "validateFnscript", "fnvalidation()",
true);

Related

Delaying Calling JQuery or javascript method from c#

I've got a mixture of JQuery and Ajax partial postbacks on a webforms page and I'm trying to stop the user navigating away from a page without their changes having been saved.
It's working pretty well unless one of the data validators on the page is invalid. There is a jquery method on the submit button that basically nulls the onbeforeunload event. In the event that the validators are invalid, I dont want that to happen, so I turned off the client side validation, and in the method, called Page.Validate(), then if the page was invalid, I tried to register a startup script as described here to reset like so:
if (!Page.IsValid) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "setConfirmUnload(true);", true);
return;
}
If I run the click submit and the page is invalid, the call to setConfirmUnload(true) happens, but the method cant be found (presumably because I re-set this up every time a postback happens?
The actual error is " JavaScript runtime error: 'setConfirmUnload' is undefined", possibly because the bindEvents() hasnt yet re-run and therefore created it?
I thnk my problem stems from the fact that I am using partial postbacks and autopostbacks, setting up data as the user modifies the form. By default that blitzes my jquery, so I rebind the jquery calls on document.ready() as well as on postback using
<script type="text/javascript">
// attach the event binding function to every partial update
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (evt, args) {
bindEvents();
});
</script>
And my Bind Events method looks like:
function bindEvents() {
// stuff removed for brevity here...
$(function () {
// Prevent accidental navigation away
$(':input, select').bind(
'change', function () { setConfirmUnload(true); });
$('.noprompt-required').click(
function () { setConfirmUnload(false); });
function setConfirmUnload(on) {
window.onbeforeunload = on ? unloadMessage : null;
}
function unloadMessage() {
return ('You have entered new data on this page. ' +
'If you navigate away from this page without ' +
'first saving your data, the changes will be lost.');
}
window.onerror = UnspecifiedErrorHandler;
function UnspecifiedErrorHandler() {
return true;
}
});
}
If that's the case, is there a way I can force the script to run after the bindEvents() call has happened?

Executing Server-Side Methods by Clicking on a DIV

I'm working on an ASP.Net project, with C#.
Usually, when I need to put Buttons that will execute some methods, I will use the ASP Controller (Button) inside a runat="server" form.
But I feel that this really limits the capabilities of my website, because when I used to work with JSP, I used jquery to reach a servlet to execute some codes and return a responseText.
I did not check yet how this is done in ASP.Net, but my question concerns controllers and the famous runat="server".
When I add a runat="server" to any HTML Element, I'm supposed to be able to manipulate this HTML element in C# (Server-Side), and this actually works, I can change the ID, set the InnerText or InnerHtml, but the thing that I can't get, is why can't I execute a method by clicking on this element?
The "onclick" attribute is for JavaScript I think, and OnServerClick doesn't seem to work as well. Is it something wrong with my codes? or this doesn't work at all?
You will have to handle the click in the div using the Jquery and call
server-side methods through JQuery
There are several way to execute server side methods by clicking on a div or anything on your page. The first is mentioned __dopostback, second is handling the click in javascript or with jQuery and calling a function in a handler or a page method in a webservice or a page method in your page behind code.
Here is the handler version:
$("#btn1").click(function() {
$.ajax({
url: '/Handler1.ashx?param1=someparam',
success: function(msg, status, xhr) {
//doSomething, manipulate your html
},
error: function() {
//doSomething
}
});
});
I think the second version is better, because you can make a partial postback without any updatepanel, asyncronously. The drawback is, the server side code is separated from your page behind code.
Handler:
public class Handler1: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var param1= context.Request.QueryString["param1"];
//param1 value will be "someparam"
// do something cool like filling a datatable serialize it with newtonsoft jsonconvert
var dt= new DataTable();
// fill it
context.Response.Write(JsonConvert.SerializeObject(dt));
}
}
If everything is cool, you get the response in the ajax call in the success section, and the parameter called "msg" will be your serialized JSON datatable.
You can execute a method from jquery click in server, using __doPostBack javascript function, see this threat for more details How to use __doPostBack()
Add this code in your jquery on div onclick and pass DIv id whcih call click
__doPostBack('__Page', DivID);
On page load add this code
if (IsPostBack)
{
//you will get id of div which called function
string eventargs = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(eventargs))
{
//call your function
}
}
Make the div runat="server" and id="divName"
in page_Load event in cs:
if (IsPostBack)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "divClick")
{
//code to run in click event of divName
}
}
divName.Attributes.Add("ondivClick", ClientScript.GetPostBackEventReference(divName, "divClick"));
Hope it helps :)
if you are referring to divs with runat="server" attributes, they don't have onserverclick events, that's why it doesn't work

asp:dropdownlist change dynamically

Is there any chance, when I select a row from asp:dropdownlist, dynamically change page, execute sql query and after result, change selected row in second asp:dropdownlist?
If this isn't possible only with asp.net and codebehind, please let me know how to execute SELECT-query in javascript (may be with Ajax; but I don't understand it) and change second dropdown's selected row.
Thanks!
Its a bit of a generic question because there is a couple of options that you could do plus I'm not 100% sure what you want to do. In short you could use AJAX to contact a PHP page which will do an operation on your database. A result it generated and sent back to the client. You could use JSON to hold the data that is getting sent to the browser.
All AJAX does is allow you to get data from another location based on the URI you give. I would use the JQuery library as it makes it easy to implement AJAX.
// This will trigger ajax whenever the is a change in the drop down. I am assuming the drop down class is .dropdown
$('.dropdown').change(function() {
$.ajax({
type: "POST",
url: "page_change.php",
data: { name: "about_us" }
dataType:JSON,
success: function(data) {
//The data returned from test.php is loaded in the .result tag
$('.result').html(data.html);
// If you want to change page you would execute
window.location(data.url);
}
});
});
page_change.php will then contact your database and generate JSON.
More information about JQuery AJAX here:
http://api.jquery.com/jQuery.ajax/
You will need to look at JQuery, AJAX, PHP and JSON to change data on your page.
If you just want to change page on a drop down change I suppose you could store the page name in the option id?
$('.dropdown').change(function() {
var page = $(this).attr('id');
window.location(page + ".html");
});

How to call javascript method in asp.net web application

I want to use a javascript function inside a c# function
protected void button1_Click(object sender,EventArgs e){
//javascript function call ex.
/*
boolean b=the return of:
<script type="text/javascript">
function update() {
var result = confirm("Do you want to delimit the record?")
if (result) {return true;}
else {
return false;
}
}
</script>
*/
}
how can i do such a thing? i want when user press yes return true and i know he pressed yes...can i do so?
If you're trying to add JavaScript to your page from asp.net, you can use the ClientScript class.
string script = "function update() { var result = confirm(\"Do you want to delimit the record?\") if (result) {return true; } else { return false; } }";
ClientScript.RegisterClientScriptBlock(this.GetType(), "someKey", script, false);
If you're trying to call (client side) JavaScript functions from your asp.net code behind, then absolutely not. When the page posts and your C# is run, any JavaScript that was on the page no longer exists.
You're mixing two different technologies. C# runs on the server. It renders an HTML page (which may include Javascript). This page is then sent to a client's browser, where Javascript finally gets executed.
In Javascript you can prompt user about record deletion or whatever, and then you have to either navigate to another page or use AJAX to send result to the server.
I suggest that you get a good ASP.NET book. It will clear many uncertainties for you.
If you're putting this message on an <asp:Button> with postback just add the confirm dialog to the OnClientClick attribute like so:
<asp:Button ID="Button1" runat="server"
OnClientClick="return confirm('Do you want to delimit the record?');" />
If you're simply trying to create the functionality of letting the server know that a button was clicked, you're over complicating things. If you really need to dynamically insert Javascript then what Adam mentioned is worth looking into. But I highly doubt that this is the correct approach for what you're trying to do.
You should really only dynamically insert Javascript when you're worried about performance AND you have a lot of content to send.
If dynamically inserting Javascript (ie. lazy loading) is not your main concern, then here is a very simple example of what most folks would usually do to achieve the functionality you're aiming for.

To get controls inside static function

I am calling function in codebehind from javascript using webservice.
function GetAdmissionType()
{
InitComponents();
var type="";
type=document.getElementById(dlAdmissionType.id).value;
document.getElementById(hdnAdmissionType.id).value=document.getElementById(dlAdmissionType.id).value;
else if(type=="2")
{
InitComponents();
ViewResettingPanel()
makeFavorite(1);
}
}
function makeFavorite(id) {
PageMethods.SaveInfo(id, CallSuccess, CallFailed);
}
// This will be Called on success
function CallSuccess(res, id) {
alert(destCtrl);
}
// This will be Called on failure
function CallFailed(res) {
alert(res.get_message());
}
Following is my code in codebehind
[System.Web.Services.WebMethod]
public static void SaveInfo(String Id)
{
//to get textbox in form
}
Problem is iam not getting controls in aspx page in SaveInfo.Can anybody help to access controls in form inside saveinfo?
Static page methods cannot get the page's control tree. (They don't receive ViewState)
You will need to use an UpdatePanel.
You can make an asp:Button inside a <div style="display:none> with a regular Click event, make an UpdatePanel triggered by the button, and use Javascript to simulate a click of the button.
Alternatively, you could send the values of the controls that you need as parameters to your page method in Javascript. This will be more efficient than using an UpdatePanel.
You can't.
Your WebMethod is static, meaning it exists once, for all instances of your page class. It has no notion of any individual instance of your Page.
If you need to post your page back, you'll need to actually use postbacks, and not web service calls.

Categories

Resources