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
Related
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);
I am trying to pass parameter to one function in the code behind in C# from javascript
<script type="text/javascript">
$(document).ready(function () {
$("#some_id").click(function () {
var id = document.getElementById('HiddenField2');
var a = <%=btn_Click(id)%>;
});
});
</script>
<asp:HiddenField ID="HiddenField2" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "item_id")%>' />
code behind
public string btn_Click(String item_id)
{
/*do some thing*/
return null;
}
But this piece of code always giving me error of context. That id is not defined in this context.
Can some please let me know what wrong i am doing?
First, var id is javascript and the code within <%= %> is C#. You can't pass a variable between the languages like that.
Second, the value of id in this case is going to be a DOM element which C# can't use anyways. If you want to get the value of HiddenField2 within the code behind you can use HiddenField2.Value.
Third, since you're using ASP.net, instead of using jQuery's .click handler you should use the onServerClick attribute to wire up the button click behavior to btn_Click.
The button click event in C# will be triggered by Postback when your browser post data back to asp.net
I do not understand why you use HiddenField here,so my suggestion do not consider about it
Solution 1:
first you can extract your code in btn_Click to a HttpHandler(*.ashx in asp.net),then use Ajax by using js framework like jQuery to send data to your HttpHandler,data returned by HttpHandler can be processed by js
sample code is here
Solution 2:
if your code in btn_Click is relevent to your page, just use ajax Get method, the data will send to your page,the data returned by your data will be processed by js too
In the end, if you are new to web, I recommend you to learn or implement asp.net MVC, in my opinion, it is more flexible than asp.net webform
Here is the context:
I am building a .aspx page that allows the user to administrate some xml documents we have on our server. The page content is loaded using AJAX, so buttons and forms are dynamically added to the document.
If I had static buttons that I was creating within the .aspx page before it loads on the client's machine, I could attach an event to it very easily. However, I'm dynamically adding and removing buttons and forms on the fly, using jQuery.
Here is a simplified example:
In the following jsFiddle, I'm pretending that the html document contains the following script:
<script language="C#" type="text/C#" runat="server">
void SaveAllChanges(Object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
clickedButton.Text = "foobar";
}
</script>
And that I have a javascript file that contains the following:
$('button.buttonGenerator').click(function() {
$('.buttonContainer').append(
'<button onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
});
Obviously the buttons I am creating can not run the function SaveAllChanges with the way it is now. I added the onclick attribute to show what I needed to happen, in a pseudo-code kind of style.
How can I make it so that dynamically added buttons can run the C# method I have defined within the script tag at the top of the document?
Here is the jsfiddle: http://jsfiddle.net/2XwRJ/
Thanks.
You can give all buttons that must save changes a common class (e.g. class="ajaxButton") and have one jQuery method that responds to click events on elements matching that class (use live so that updates to the DOM are reflected).
$("button.ajaxButton").live("click", function(){
// Perform your Ajax callback to run server-side code
});
What you need to do is use something like ..
$(document).ready(function() {
$('button.buttonGenerator').click(function() {
$('.buttonContainer').append(
'<button id="#dynamicCommentButton" onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
});
$(document).on('click', '#dynamicCommentButton', function() {
alert($(this).attr('id'));
});
});
You are not going to be able to add the buttons like you have it there as this code here is just adding it as an HTML DOM element and the onclick attribute will be the on the client element. As a result clicking the button will try fire a SaveAllChanges javascript function
$('.buttonContainer').append(
'<button onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
What would be best would be to create that SaveAllChanges function in javascript and then you can handle it from there. Two of the ways I see you being able to do this are:
Have a http endpoint setup (script service, web api or just posting to a page) that you call using Ajax from your javascript. You can then pass through any needed arguments.
You could have a hidden element and hidden button on the page so that when the javascript is called it populates any arguments you need and then clicks the hidden button and posts the page back.
Personally I would choose the first approach from a user experience stand point as the page will not be posting back each time. I have used something similar to the second approach and it works fine but just feels very clunky.
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.
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.