Call server method using JavaScript or jQuery - c#

I wanted to know if you can call server side method using JavaScript or jQuery whilst doing a postback?
I have created a anchor button and want it to work same way as a linkbutton i.e. do postback and call a event. So i thought it could be possible of using JavaScript?
How would i do this? I have done alot of searches on net but could not find anything..
;

Have you tried searching for ajax?
http://api.jquery.com/category/ajax/
There's lots of tutorials online. If you're using dot net then there's also a JQuery plugin called dot net ajax which I find really useful. However ajax is a huge topic and your question is really broad so it's hard to be more specific!

What you could do is send an AJAX call to the server. But it's a really big topic, you can find a lot of information on the internet.
The simplest form with jQuery is
<a href="javascript:void(0);" id="SOMEID" >Call the server</a>;
$('#SOMEID').click(function(){
$.get('url/on/server', function(data){
//do something with data returned from server
});
});
This makes an Asynchronous call to the url url/on/server and then waits for an answer (since the call is Asynchronous the user can keep on doing things on the page)

Okay you need to postback. Take a look at this article --> http://weblogs.asp.net/mnolton/archive/2003/06/04/8260.aspx
The only catch is you have to call the GetPostbackReference every time a postback happens.

If you want to do postback from anchor tag using javascript, you can do
document.forms[0].submit(); //This will post your form
OR
__doPostBack();
OR
If you want to know which control caused postback.
JavaScript
function __doPostBack(eventTarget, eventArgument) {
var theform;
if (window.navigator.appName.toLowerCase().indexOf("n etscape") > -1) {
theform = document.forms["Form1"];
}
else {
theform = document.Form1;
}
theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
theform.__EVENTARGUMENT.value = eventArgument;
alert(theform.__EVENTARGUMENT.value);
theform.submit();
}
With following ASPX code to make it work
<input type="hidden" name="__EVENTTARGET" />
<input type="hidden" name="__EVENTARGUMENT" />
Hope this is what you are looking for.

Related

How to call javascript function and c# code on asp:button?

When a user clicks a button on ASP.net page, I need to
Save file from asp:fileUpload in a folder on a server - I guess this needs to be done in C#, like in How to correctly use the ASP.NET FileUpload control
Run a javascript function like in How to call javascript function from asp.net button click event
Is there a way to combine C# and Javascript to achieve what I need? If not, how should I do it?
Try using the onClientClick property of the asp:button element.
Ex, on your .aspx file:
<script type="text/javascript">
function myFunction()
{
alert('hi');
}
</script>
...
<asp:button id="Button1"
usesubmitbehavior="true"
text="Open Web site"
onclientclick="myFunction()"
runat="server" onclick="Button1_Click" />
And in your code behind (.aspx.cs)
void Button1_Click (object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
}
}
More info at
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
Note that no JavaScript actually "runs" until the server-side code (C# in this case) has entirely completed and the resulting page is returned to the client. Once that page renders on the client, then JavaScript runs on the client.
So in order to execute your JavaScript code, all you need to do is include it in the page being returned to the client. There are a number of ways to do this, and the options depend on whether you're using WebForms or MVC.
You might use something like RegisterStartupScript in WebForms, for example. Or, you could just have the JavaScript code exist in a PlaceHolder control with Visible=false and only make the control visible in the response which intends the JavaScript code to run. (Roughly the same method is also easily usable in MVC by just wrapping the JavaScript code in a server-side condition to determine whether to render it or not.)
The main thing to remember is that you're not "running the JavaScript code from C#" or anything like that. There's a hard separation between server-side and client-side code. The server-side code ultimately builds the page that it sends back to the client, and that page can include JavaScript code to run on that client.

Good Practice mvc conditional button and its code

I'm coding an MVC3 application with ajax and I got a situation.
I have to show na Button only if an condition is true. Ok its easy to do.
#if (Model.AAA == ENUM.AAA)
{
<button>OK</button>
}
but this button going to call an ajax function.
Now my doubt is, WHERE A PLACE MY AJAX CODE?
if I do this:
#if (Model.AAA == ENUM.AAA)
{
function OK(){
$.ajax({});
}
<button>OK</button>
}
it's sound ugly code!!!
It's seens that the code it' not in the right place but the ajax code is "safe", I mean, the ajax code will only exist if the button exist.
but if I place my code in head section, An advanced user will be able to call the ajax function.
or if a make an #if clause to enclose the script, I will duplicate code like this
<head type="text/javascript">
#if (Model.AAA == ENUM.AAA){
function OK(){
$.ajax({});
}
}
</head>
....
<body>
....
#if (Model.AAA == ENUM.AAA)
{
<button onclick="OK()">OK</button>
}
....
</body>
So, What is the best practice to face this situation, the best approach?
It sounds almost like you are wanting to use the presence/lack of a snippet of Javascript code to control access to a call on your server. Don't do that.
Your server should always be evaluating if the action can be called by the user in question at that moment. What if the user leaves the page open in their browser, and some application state change happens that would block the user from calling that action... but their browser is still displaying the button? Or if a clever user decides to play around with your URLs by poking around in the source?
I would recommend just putting the javascript in a common location and calling it from there, as that keeps all your Javascript together.
Just have the one conditional in your markup, like you have:
#if (Model.AAA == ENUM.AAA)
{
<button id="OkButton">OK</button>
}
Then tweak your Javascript slightly so you don't include Razor (that way it can be extracted into an external JS file):
<head type="text/javascript">
WireUpButton();
function WireUpButton() {
var okbutton = document.getElementById("OkButton");
if (okbutton) {
okbutton.onclick = OK;
}
}
function OK(){
$.ajax({});
}
</head>
The server should control the request call and check for the correct state. #Andrew Barber points this out, but that is not just leaving the browser open. But the advanced user could share the ajax request, with others that don't have permission, or use it maliciously
Trying to answer the question in a bit more depth, it could be not a simple script like this, but a file or some JS library, maybe you don't have control about the server you ajax is accessing. In that case, you'd probably want to duplicate the verification.

posting a form but without posting the viewstate

I have a web form and want to 'get' it to another page..
is there anyway to submit it without posting the ViewState and other bits I don't want?
Or should I be catching the submit button click and redirecting with a querystring I build myself.
You have a couple of options here:
Disable ViewState
Use jQuery to remove the fields you don't want to post before the are sent to the server
You don't have to disable ViewState on all pages, just the pages that you do not care for the state to be saved.
But there is also the option to disable the ViewState completely if you never want to use it.
If you just want to compose a GET by yourself, you can use jQuery for that aswell so you only pass the parameters you really want which will give you 100% control of what is posted /getted.
If you are not using the viewstate, why have you kept it enabled? Just disable it. For every server control, set the EnableViewState = False and you are free from it. If you need the viewstate, it will be part of the post all the time.
There are different ways to persist viewstate.
I have had in the past, had to persist viewstate on the server (using ApplicationState/Session, cant remember) for a heavy AJAX page to support faster updates. Works well.
See Page.LoadPageStateFromPersistenceMedium and Page.SavePageStateToPersistenceMedium.
Sorry, no links from Reflector available.
You could add an event handler to your search button and do something similar to this
private void button_Click(object sender, EventArgs e)
{
String query = queryTextBox.Text;
Response.Redirect("SearchResults.aspx?query=" + query);
}
Using JavaScript
function doSearch()
{
// Assuming you are not using jQuery,
// using jQuery it would be $('#queryTextBox').value instead
var queryString = document.getElementById('queryTextBox').value;
window.open("SearchResults.aspx?query=" + queryString);
return false;
}
Html
<input type="text" id="queryTextBox" />
<input type="button" onclick="return doSearch()" value="Go" />

Asp.Net:Light ajax (get) call that doesn't rerender the page?

Let say I have:
<asp:ImageButton ID="btnNoticeClose" runat="server"
ImageUrl="~/img/btn_spara_green.gif" ToolTip="Stäng"
OnClientClick="jQuery('#Notice').hide();"
Click="btnNoticeClose_Click"/>
How do I call a btnNoticeClose_Click without rerendering anything? As I don't need to rerender anything I don't want to use an UpdatePanel? or do I?
try:
OnClientClick="jQuery('#Notice').hide();return null;"
or write full function in js:
function CloseThis()
{
$("#Notice").hide();
return true;
}
OnClientClick="javascript:CloseThis();"
EDIT:- Well you want to call server side method as well and don't want to render anything. Then only option left is using page method and using jQuery AJAX. Please head here to Dave's blog for more information on this.

Detect if a page is within a iframe - serverside

How can I detect server-side (c#, asp.net mvc) if the loaded page is within a iframe? Thanks
This is not possible, however.
<iframe src="mypage?iframe=yes"></iframe>
and then check serverside if the querystring contains iframe=yes
or with the Referer header send by the browser.
Use the following Code inside the form:
<asp:HiddenField ID="hfIsInIframe" runat="server" />
<script type="text/javascript">
var isInIFrame = (self != top);
$('#<%= hfIsInIframe.ClientID %>').val(isInIFrame);
</script>
Then you can check easily if it's an iFrame in the code-behind:
bool bIsInIFrame = (hfIsInIframe.Value == "true");
Tested and worked for me.
Edit: Please note that you require jQuery to run my code above. To run it without jQuery just use some code like the following (untested) code to set the value of the hidden field:
document.getElementById('<%= hfIsInIframe.ClientID %>').value = isInIFrame;
Edit 2: This only works when the page was loaded once. If someone have idea's to improve this, let me know. In my case I luckily only need the value after an postback.
There is no way of checking this that will fit your requirement of "secure" as stated in your comment on #WTP's answer.
I don't think the server-side can do this, so why not put a hidden control in your page that will be in the iframe? When the URL in the iframe loads, you can add some client-side code to set the hidden input to indicate you are in an iframe. The easiest check would be on the client-side in an onload method, like this:
// Set hidden input
someHiddenInput.value = self != top
It's more secure than the querystring, but it still might not be enough security for you.
My 2 cents.
Old question but why not a more simplistic approach like
var isFramed = self !== parent

Categories