div inner html using c sharp static method? how to - c#

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

Related

Sending value in ajax call and reading it in page load

I'm making an ajax call in the function as below
function UploadPic() {
debugger;
// generate the image data
var canvas = document.getElementById("canvas");
var dataURL = canvas.toDataURL("image/png");
// Sending the image data to Server
$.ajax({
type: 'POST',
url: "baseimg.aspx",
data: { imgBase64: dataURL },
success: function () {
alert("Done, Picture Uploaded.");
window.opener.location.reload(true); // reloading Parent page
window.close();
window.opener.setVal(1);
return false;
}
});
}
And in the page load I'm trying to get the value as
protected void Page_Load(object sender, EventArgs e)
{
StreamReader reader = new StreamReader(Request.InputStream);
string Data = Server.UrlDecode(reader.ReadToEnd());
reader.Close();
}
In the dataURL I'm getting the value but in the page load 'string Data' is coming as empty.
I have referred to Capturing Image From Web Cam in ASP.Net to make this functionality.
The ajax is hitting successfully to the code then coming back and executing the success portion in the ajax call.
I'm finding no way out of it.
Since it is a POST operation, try checking the form variable like the following for the data string:
Request.Form["imgBase64"]

Wait until ClientScript.RegisterStartupScript is finished

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

Pass variable value calling c# behind function with javascript in asp.net

this is my scenario: I have an asp website that can merge tiff file. So, to do this i need to use a c# function and it is called after a javascript event.
The c# is like this:
public void mergeImages(string initialUrl, string lastImageUrl)
{....}
I created two hidden field like this:
<input type="hidden" id="hi1" value="D:\\ProvaUpload\\1.tif" />
to get the value to pass at the function, because I didn't know in which way I can pass js variable to it.
I call the function in this way:
'<%mergeImages(par1,par2); %>';
In which way can I pass variable value to the function?
Decorate the method with WebMethod Attribulte:
[WebMethod]
public void mergeImages(string initialUrl, string lastImageUrl)
{....}
Get the hidden fields, and pass these to Jquery Ajax call, from a button click
var hdn1 = $('#hi1').val();
var hdn2 = $('#hi2').val();
var parameters = '{initialUrl:' + hdn1 + ', lastImageUrl:' + hdn2 + '}';
$.ajax({
type: "POST",
url: "page.aspx/mergeImages",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
}
});
Refer the stackoverflow thread.
ASP.NET - Passing JSON from jQuery to ASHX
This will help you to understand to use handler file (ashx) to do ajax json request.
your requirement can be achieved with this concept.
you do not need to call cs method into javascript. you should post using ajax on any kind of handler file e.g ashx, asmx, or any other service .
Nothing to do much you just need to take an extra button which will be hide in output:
<asp:button id="btnGetAndPassvalues" runat="server" Text="hide" Onclick="btnGetAndPassvalues_Click" Style="display:none"/>
Now javascript function should be like below:
<script>
$('[id$=btnUpload]').live('click', function (e) {
// code to finish Upload prosess
$('[id$=btnGetAndPassvalues]').click();
});
</script>
That's all and in click event get the values of hidden field:
protected void btnGetAndPassvalues(Object sender,EventArgs e){
string hd1=hiden1.Value;
string hd2=hiden2.Value;
}
or you can make AJAX Call,
one of the easy way to achieve this :-
As you already have two hidden fields but must add runat attribute to it ,so that
you can get their values at server side. Let's Say:-
<input type="hidden" id="hi1" value="D:\\ProvaUpload\\1.tif" runat="server" />
<input type="hidden" id="hi2" value="D:\\ProvaUpload\\2.tif" runat="server" />
and Make a hidden button :-
<asp:button id="btnhidden" runat="server" Text="hide" Onclick="btnhidden_Click" Style="display:none"/>
Now you can click the button in javascript function :-
function UploadFinished()
{
//your JS code:-
// After finish uploading ..Click the button .. i have used jquery for simplicity:-
$('input[id$="btnhidden"]').click();
}
Now in your code behind :-
protected void btnhidden_Click(Object sender,EventArgs e)
{
// you can get hidden fields values here ....
string val1=hi1.Value;
string val2=hi2.Value;
// Call your merge function here :-
mergeImages(val1,val2);
}

How to call jquery function in a class file

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 <%= %>.

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?

Categories

Resources