i have problem with execute page methods when i upload my website on Plesk panel .
my code in page.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
and i call java script like
function checkUserMeliCode(meliCode)
{
PageMethods.IsMeliAvailable(meliCode, onSucceeded);
}
function onSucceeded(result, userContext, methodName) {
if (methodName == "IsMeliAvailable") {
if (result == true) {
spanAv.innerHTML = "<span style='color:green'> <li class='fa fa-check' ></li> معتبر </span>";
}
else {
spanAv.innerHTML = "<span style='color:Red'> <li class='fa fa-warning' ></li> قبلا ثبت گردیده است </span>";
}
}
and i have this code in code behind
[WebMethod]
public static bool IsMeliAvailable(string Meli)
{
Admin_Req tbl_Admin = new Admin_Req();
tbl_Admin.Req_MeliCode = Meli;
DataTable result_req = tbl_Admin.Get_ReqByMeliCode();
if (result_req.Rows.Count>0)
{
return false;
}
else
{
return true;
}
}
every thing work good until i upload my web site to panel Plesk version 9.5
any solution ?
i think i have to add something to web.conf to allow plesk send and receive PageMethod
it's link of uploaded code
website Link
Webmethod call for 4th input it's kind of number, and i call pagemethod when number count equal 10 . so fill it until it's count equal 10 and look at console
the page method need to set path ... if you don't set path for page method it will get current page ...
in conclusion when you upload your website to your host . you have to set page method path .
PageMethods.set_path("pages/AdminReq.aspx");
Related
I have a static method where I want to get the "div" inner html I Used the following method
[WebMethod]
public static string SetFileNameU(List<string> someValues)
{
string linkmain = link.Replace("Journey=R", "Journey="+journey);
SearcResult src = new SearcResult();
src.iframesourceType(linkmain);
return linkmain;
}
and here i called non static function passing link to that fucntion
public void iframesourceType(string linksrc)
{
frame.InnerHtml = ""; //// error frame is null
}
and returns the error
object refrence not set to initialization of object
my html frame is div
<div runat="server" id= "frame" class="col-md-9">
<%--<iframe class="ifr" >
</iframe>--%>
</div>
kindly tell me how to change content my webform class is searchresult.cs and frame.innerHtml was working at form laod and can be aceesed but calling from static after ajax call in non static function it works
why static?
1-first time when i open file i use that
protected void Page_Load(object sender, EventArgs e)
{
string link = Convert.ToString(Session["url"]);
Label1.Text = link;
SomewhereInTheCode();
frame.InnerHtml = (" <iframe class='ifr' frameborder='0' src='" + link + "' > </iframe>");
}
now i am using ajax call to web method to change inner HTML as needed see the code at top and it work only at page load
div is runat server so acesed from server side as frame
You Cannot access any of the form elements in a static method. Only instanciable methods can access it.
If you want to change the content of div through web method just return the content and then assign the HTML to div in the success function of Ajax Call.
Ajax Function
$.ajax({
url : "FileName.aspx/SetFileNameU",
method : "GET"/"POST",
data : "{someValues:['value1','value2','value3']}",
success : function (data) {
$('#frame').html(data);
}
});
I'm converting my JavaScript code to ASP.NET code, but I ran into an issue.
I still use JS code to show the user a prompt window (Using JS code in code behind).
The JS code gets executed and the input of the user gets saved in a hiddenfield.
After the code I read the value from the hiddenfield and save that in a string to use later.
The problem is that the code for reading the hiddenfield value gets executed before the JS code has been executed, which results in an empty string.
How can I let my code what until the JS code has been completely executed?
ClientScript.RegisterStartupScript(this.GetType(), "prompt", "var value = prompt('Enter your password here.'); storeinput(value);", true);
string code = hidValue.Value;
Debug.WriteLine("Password: " + code);
Thanks!
Put ScriptManager in asp.net page Like this
<asp:ScriptManager ScriptMode="Release" LoadScriptsBeforeUI="false" EnablePageMethods="true"
runat="server" ID="ScriptManager1" />
create method in page and decorate [WebMethod] attribute
[WebMethod]
public static void GetPasswordFromClient(string password) {
Debug.WriteLine("Password: " + password);
}
and write this code in javascript :
function OnSucceeded_SendPasswordToServer(result, userContext, methodName) {
}
function OnFailed_SendPasswordToServer(error, userContext, methodName) {
alert(error);
}
function SendPasswordToServer(string password) {
PageMethods.GetPasswordFromClient(password, OnSucceeded_SendPasswordToServer, OnFailed_SendPasswordToServer);
}
and now you can use register script or in your page use :
var value = prompt('Enter your password here.');
SendPasswordToServer(value);
I've got a webpage that people in my company are filling in using mobile handsets. Only problem is, if they move out of a signal area, then when they try and update their work the page will go to a "page not found" and they'll lose the work they've filled in.
I'm trying to remedy this and, at the moment, have this solution:
protected void Button1_Click(object sender, EventArgs e)
{
Session["Online"] = 0;
CheckConnect();
if ((int)Session["Online"] == 1) { Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alertMessage", "alert('You are currently online')", true); }
if ((int)Session["Online"] == 0) { Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alertMessage", "alert('You are currently offline')", true); }
}
protected void CheckConnect()
{
System.Uri Url = new System.Uri("http://www.mypage.com/pixel.jpg?" + DateTime.Now);
System.Net.WebRequest WebReq;
System.Net.WebResponse Resp;
WebReq = System.Net.WebRequest.Create(Url);
try
{
Resp = WebReq.GetResponse();
Resp.Close();
WebReq = null;
Session["Online"] = 1;
}
catch
{
WebReq = null;
Session["Online"] = 0;
}
}
Now, this will check if the pixel file at www.mypage.com exists (no, that's not actually my page, I've substituted it for this example) and, if so, it returns a 0, if not a 1. Which is fine and dandy.
However, pressing the button causes the page to be reloaded. Then, if it's offline, it does the usual "page not found" business. My button code is here:
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
Basically, I want it to not reload the page if we're offline (or indeed if we are online, as the code that does the updating handles that part anyway).
EDIT - alright, different approach now. Doing this entirely through javascript using the following:
<asp:Button ID="Button1" runat="server" OnClientClick="ifServerOnline()" Text="Button" />
<script type="text/javascript">
function ifServerOnline(ifOnline, ifOffline)
{
var img = document.body.appendChild(document.createElement("img"));
img.onload = function ()
{
ifOnline && ifOnline.constructor == Function && ifOnline();
};
img.onerror = function ()
{
ifOffline && ifOffline.constructor == Function && ifOffline();
};
img.src = "http://www.mypage.com/pixel.jpg?" + Date.now;
}
ifServerOnline(function ()
{
return confirm('Online');
},
function ()
{
return confirm('Offline');
});
</script>
Unfortunately still causing a page refresh.
In your page's javascript assign form onsubmit event handler, where you cancel default submit. Also, in this event handler, issue an ajax request to the server with a very brief response. In onsuccess event handler of this ajax request - resubmit the form, in onerror handler - tell the user that they lost connection to server.
You can't do postback to the server when you offline.
No way to do it..
But maybe you can do that's with javascript.. try this way.
Managed it with this...
<asp:Button ID="btnRouteC" runat="server" OnClientClick="return ifServerOnlineA(ifServerOnlineA1, ifServerOfflineA1);" Text="Route" Width="45%" />
<script type="text/javascript">
function ifServerOnlineA(ifOnline, ifOffline)
{
var img = document.body.appendChild(document.createElement("img"));
img.onload = function ()
{
ifOnline && ifOnline.constructor == Function && ifOnline();
};
img.onerror = function ()
{
ifOffline && ifOffline.constructor == Function && ifOffline();
};
img.src = "http://www.myserver.com/pixel.jpg?" + Date.now;
return false;
}
function ifServerOnlineA1()
{
document.getElementById('btnRoute').click();
return false;
}
function ifServerOfflineA1()
{
alert("There is no connection at the moment. Please try again later.");
return false;
}
</script>
As Itiel said, it won't work through the codebehind but will through the Javascript.
Trying to invoke this web service using AJAX...
The web service is as follows
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public String countryCode(String input)
{
StringBuilder strings = new StringBuilder("", 10000);
String text = System.IO.File.ReadAllText(Server.MapPath("countryCodes.txt"));
String[] countries = Regex.Split(text, "#");
var valids = new List<String>();
foreach (String c in countries)
{
if (c.ToUpper().StartsWith(input.ToUpper()) || c.ToLower().StartsWith(input.ToLower()))
{
if (input == "")
{
break;
}
valids.Add(c);
}
}
return (valids.Any()) ? String.Join(" ", valids) : "No results found for your input!";
}
}
I have set up an empty web form and called the service reference in the script manager like so
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService1.asmx" />
</Services>
</asp:ScriptManager>
And I have my javascript as follows below
<script type= "text/javascript">
var a = wRequest.set_userContext("user's context");
var onClick = function () {
CountryCodes.WebService1.countryCode($get("TextBox1"), onSucess, onFailed);
}
var onSuccess = function (result) {
$get("Label3").innerHTML = result;
}
var onFailed = function (result) {
$get("Label3").innerHTML = "No results found for your input!";
}
</script>
Now my understanding is that when the button is pressed it will take the input of TextBox1's value and use it as the argument for my WebService.countryCode method and therefore if it succeeds it will set label 3 to the result of the method and if it doesn't succeed it will set label 3 to the string provided...
This however does not happen.... Infact nothing happens when I click my button, for clarity, here is my button declaration...
<input type="button" value="Find Country Codes " onclick ="onClick()" />
This button is in the same place the automated textbox1 and label code is generated.
So my question is, what have I done wrong and how can it be fixed?
Any clarifications needed just post below thank you.
Regards
EDIT : yes I have commented out this line in the web service
"[System.Web.Script.Services.ScriptService]"
Decorate your web service class with [System.Web.Script.Services.ScriptService], like this:
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
This allows your web service to be called by your JavaScript.
Also, change your call to the web service to remove the CountryCodes prefix, like this:
var onClick = function () {
WebService1.countryCode($get("TextBox1"), onSucess, onFailed);
}
I use the JQuery Validation plugin to validate a form (http://docs.jquery.com/Plugins/Validation/)
For example, I can validate an email in a form.
What I would like to do is to validate if the username chosen already exists. So, I need to call a server method that query the database. How can I do that ?
UPDATE
From balexandre answer, I try the following :
$.validator.addMethod("userName",
function(value, element)
{
$.get
(
"CheckUser.aspx?User=" + value,
function(data)
{
if (data == "True")
{
return false;
}
else if (data == "False")
{
return true;
}
else
{
alert(data);
}
}
);
},
"User already exists");
$(document).ready
(
function()
{
$("#aspnetForm").validate
(
{
rules:
{
<%=txtUserName.UniqueID %>:
{
required: true,
email: true,
userName: true
}
}
}
);
}
);
In the Response, I write a boolean (True of False) instead of 1 ou 0.
I know that my validation function is call. The problem is that it's always show the error message even if the user doesn't exists. I try to put an alert message before the return true to see if it's reach, and it is. So I don't get, why it's doesn't work...
quite easy and it's a nice thcnique that I apply a lot over my projects
1 - create an aspx page called verifyUserAvailability.aspx with code-behind file
2 - delete all lines except the first in the aspx file
3 - in the code-behind file inside the Page_Load event call your database like
protected void Page_Load(object sender, EventArgs e) {
string username = Request["usr"];
int r = 0;
if(!String.IsNullOrEmpty(username))
if( yourDAL.getUserAvailability(username) )
// your method would send true if user is available to be used
r = 1;
Response.Clear();
Response.Write(r);
Response.Flush();
}
4 - now in your form page, create a button like
<input id="btnCheckAvailability" type="button"
value="Check availability"
onclick="javascript:checkAvailability();" />
5 - create the checkAvailability() method
<script type="text/language">
function checkAvailability() {
var $user = $("#UsernameInputBox");
$.get("verifyUserAvailability.aspx?usr=" + $user.val(), function(data) {
// this will call the page passing the username and return 1 or 0
if( data == "1" )
$user.css("background-color", "green");
else
$user.css("background-color", "red");
});
}
</script>
This should do the trick...
http://riderdesign.com/articles/Check-username-availability-with-JQuery-and-ASP.NET.aspx
OR...
One answer shows how to call a service & the second shows how to call a page method.
Calling an ASP.NET server side method via jQuery