How to call jquery function in a class file - c#

Hi all I have created a javascript which I want to use in my entire application, so I have created a class which returns string as follows
public static string ShowAlert(string pHeader, string pMessage)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script language='JavaScript' type='text/javascript'>");
sb.Append("example1('" + pHeader + "','" + pMessage + "')");
sb.Append("</Script");
return sb.ToString();
}
This is my code JFunction.JS
(function example1(title, content) {
$.msgBox({
title: title,
content: content
});
})
Now on button click I am just calling as follows
Page.ClientScript.RegisterStartupScript(this.GetType(), "",ShowAlert(pHeader,pMessage) , true);
But I am unable to get the message, so is there any way to create a unique method instead of calling the script on each page,

Code Behind
public partial class call_jquery_from_class_file : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Alert.ShowAlertMessage("Testing Code", Page);
}
}
Class file Code
public class Alert
{
public static void ShowAlertMessage(string error, Page page)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("$(document).ready(function() {");
sb.AppendLine(" $(\"form\").append($(\"<div>\").attr(\"id\", \"dialog\").css(\"display\", \"none\").html('"+error+"'));");
sb.AppendLine(" $(\"#dialog\").dialog({autoOpen: true,show: \"blind\",hide: \"explode\" });");
sb.AppendLine("});");
ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", sb.ToString(), true);
}
}
Hope it helps you,.
Same is working for me.That's why i suggested same.

ASP.NET Button control has Attributes property. So if you want to call javascript method on server control you just need to add "onclick" Attribute. For example you have btnAlert control:
Javascript file:
function example1(title, content) {
$.msgBox({
title: title,
content: content
});
}
ASP.NET code behind in Page Load:
btnAlert.Attributes.Add("onclick", String.Format("example1('{0}', '{1}'); return false;", "some title", "some message"));
You should add return false to prevent PostBack. BTW If you need a control only for calling client side methods you may use general html control(<button onclick='example1("<%= Resources.Title %>", "<%= Resources.Content %>")'>Example button</button>) and add your title and content by using <%= %>.

Related

How to return value from asp.net page called by jQuery Get() Method

How to return some value from asp.net page that is called using jQuery Get() method ? The get method is given below and i want the alert() should display the returned value.
The get() calls "result.aspx" page that return a string and that string i want to show in alert().
$.get("result.aspx",
{
name: "Donald Duck",
city: "India"
},
function (result, status, xhr) {
alert(result);
}
);
The result.aspx code is:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadReturn();
}
}
void LoadReturn()
{
string name = Request.QueryString["name"];
string city = Request.QueryString["city"];
string returnValue="Hello Mr."+ name + " who lives in " + city;
//How to return value of returnValue to the jquery get() function.
}
How to return value of returnValue to the jquery get() function ??
Update
I tried the response.write(). It is able to return the data to jquery get() method.
Response.Write(returnValue);
Only problem is that it is also sending me the full HTML of the result.aspx page. Which i don't want.
How can i prevent the unnecessary HTML from reaching the jquery get() method?
I solved it by putting Response.End() in the end. Hope it helps others too.
void LoadReturn()
{
string name = Request.QueryString["name"];
string city = Request.QueryString["city"];
string returnValue="Hello Mr."+ name + " who lives in " + city;
Response.Write(returnValue);
Response.End();
}

div inner html using c sharp static method? how to

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);
}
});

Textbox (and other controls) - "Object not set to an instance...."

I realize this is a common error and I've followed the many fixes to this problem offered online but have yet to find a solution.
I developed a winform app which gets JSON from an external website. I click a button control and the app goes through my json serialiser method and posts the results to a textbox and appends to a textarea.
public void RenderData(string buttonText)
{
if (buttonText == "Start")
{
EquationData deserializedData = getData("http://test.ethorstat.com/test.ashx");
var processed = new ProcessEquation();
int result = processed.Calculate(deserializedData);
string res = deserializedData.parm1 + " " + deserializedData.op + " " + deserializedData.parm2 +
" = " + result;
TextBoxResult.Text = res;
equation.Append(" " + deserializedData.parm1 + " " + deserializedData.op + " " + deserializedData.parm2 +
" = " + result + '\n');
TextAreaResults.Value = equation.ToString();
}
}
This worked fine as it was. But requirements have changed in that the app has to poll data every second. Therefore I created a wcf web service called by a jquery script to run every second.
The problem is my controls - textbox and textboxarea - generate {"Object reference not set to an instance of an object."}. My assumption is that these controls aren't being loaded now that I'm calling the method from JQuery's ajax function (?).
$(document).ready(function () {
//while ($('#eThorButton').text != "Stop") {
if ($('#eThorButton').click) {
$.ajax({
url: 'Service/eThorService.svc/getUpdate',
method: 'get',
dataType: 'json',
success: function(){
alert("success");
},
error: function (err) {
alert(err);
}
})
//delay(1000);
}
});
My controls do show in intellisense and, of course, on Default.aspx when I run it. How can I fix this?
EDIT
I solved the 'Object not set...' problem by instantiating a new textbox:
public partial class _Default : Page
{
public static StringBuilder equation = new StringBuilder();
public TextBox TextBoxTest = new TextBox();
When I debug and step through the value is set, the textbox renders but the textbox is empty. How do I fix that?
Make your method static and add annotation [WebMethod] and return list of results.
[System.Web.Services.WebMethod(EnableSession=true)]
public static List<string> RenderData(string buttonText)
{
// return result here
}
Pass parameter with data:{buttonText:yourvalue} to $.ajax call. and change the success function and assign values to your control on client side via javascript.
success : function(msg){
if(msg.d!=null){
$('#<%=TextBoxResult.ClientID%>').val(msg.d[0]);
}
}

How to send data from aspx to php page

so far i have used this code.It is working when i am sending the data from aspx to aspx.
But in case of aspx to php it is not working.....
protected void Button1_Click(object sender, EventArgs e)
{
RemotePost myremotepost = new RemotePost();
myremotepost.Url = "http://172.16.126.32/Riyas/marggroup.com/get-current-openings.php";
myremotepost.Add("field1", TextBox1.Text);
myremotepost.Post();
}
public class RemotePost
{
private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
public string Url = "";
public string Method = "post";
public string FormName = "form1";
public void Add(string name, string value)
{
Inputs.Add(name, value);
}
public void Post()
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Write("<html><head>");
System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));
System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));
for (int i = 0; i < Inputs.Keys.Count; i++)
{
System.Web.HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", Inputs.Keys[i], Inputs[Inputs.Keys[i]]));
}
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body></html>");
System.Web.HttpContext.Current.Response.End();
}
}
In case of php i have use this code:
<script runat="server">
function formload()
{
alert("its working");
if(Request.Form["field1"] != null ){
alert("its working");
Response.Write("field1 : " + Request.Form["field1"] + "</br>");
}
if(Request.Form["field2"] != null ){
Response.Write("field2 : " +Request.Form["field2"] + "</br>");
}
}
</script>
</head>
<body onload="JavaScript:formload()">
<script language="JavaScript">// change to text/javascript or even remove, no effect
window.onload = function() {
formload();
};
</script>
</body>
My aim is i want to send data from aspx to php not in the query string.
Modify your php script to contain the below given code and see if it works. You don't need anything else apart from the given two lines.
<?php
print_r($_POST);
Interesting...
in the onload function, you are calling formload(), which is a server side function , isn't it?
this is not correct, on client site you should only call client site javascript function.
if you want to post information to another server, no matter it is php/asp.net/jsp.
simply use a form....
in the Post function of your remotepost class, you didn't post to your remote server... just generate some html tags, and in the page load function, submit the form automatically,
it is not nice, but should work.
correct first issue first, then see how it goes.
If not in the query string, why not send it as POST data instead?

Jquery Notification Popups - jquery and updatepanels

Hi i want notifications to popup if the need arises. I am using an asp.net timer which checks if a new message has arrived. The problem i am getting is that the jquery notification does not show up. I am guessing this is something to do with the update panel. Because when i tried calling it from pageload it worked fine. Here is my code;
protected void updateTimer_OnTick(object sender, EventArgs e)
{
Cache Cache = new Cache();
users = Cache.getUserDetailsByUserID(Convert.ToInt32(Page.User.Identity.Name));
if (users._bNewNotification)
{
List<UserNotification> listUserNotification = null;
listUserNotification = Cache.getLatestNotifcationsByUserID(Convert.ToInt32(Page.User.Identity.Name));
foreach (UserNotification userNotification in listUserNotification)
{
StringBuilder jquery2 = new StringBuilder();
jquery2.AppendLine("$.extend($.gritter.options, {");
jquery2.AppendLine("position: 'bottom-left',");
jquery2.AppendLine("fade_in_speed: 100,");
jquery2.AppendLine("fade_out_speed: 100,");
jquery2.AppendLine("time: 3000");
jquery2.AppendLine("});");
Page.ClientScript.RegisterStartupScript(typeof(Page), Guid.NewGuid().ToString(), jquery2.ToString(), true);
StringBuilder jquery1 = new StringBuilder();
jquery1.AppendLine(" var unique_id = $.gritter.add({");
jquery1.AppendLine(" title: 'This is a sticky notice!',");
jquery1.AppendLine(" text: '" + userNotification._NotificationType + "',");
jquery1.AppendLine(" image: 'http://s3.amazonaws.com/twitter_production/profile_images/132499022/myface_bigger.jpg',");
jquery1.AppendLine(" sticky: true,");
jquery1.AppendLine(" time: '',");
jquery1.AppendLine(" class_name: 'my-sticky-class'");
jquery1.AppendLine(" });");
Page.ClientScript.RegisterStartupScript(typeof(Page), Guid.NewGuid().ToString(), jquery1.ToString(), true);
}
users._bNewNotification = false;
users.UpdateNewNotification();
Cache.RemoveUserProfileCacheByUserID(users._USERS_ID);
}
}
Can someone help me figure out what it is i am doing wrong, thanks
Your approach won't work. When the browser gets your page it disconnects, so your server-side C# timer event handler code will have no browser to talk to.
You need to do something like implement polling on the web page in client-side JavaScript. e.g.
<script>
$(document).ready(function(){
window.setInterval(function(){
$.get('path/to/GetNotifications.aspx', function(data){
// data contains text from GetNotifications.aspx
// it could be JSON, XML, CSV... it's up to you
// do something with it here...
})
},5000 /*5s*/)
})
</script>

Categories

Resources