Access ASP control from static method - javascript

I can't achieve this one:
I have a dynamically-generated table in HTML. One of the columns contains just links, it's a column that contains tags. So every link has assigned a function that makes an ajax call and communicates with an aspx:
function cargaDatosModificacion(id) {
var dto = {};
dto.idPromoBanco = id;
var dtoJSON = JSON.stringify(dto);
$.ajax({
async: false,
url: 'PromosBancos.aspx/CargaDatosModificacion',
cache: false,
dataType: 'json',
type: "POST",
data: dtoJSON,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {
},
error: errorResponse
});
}
So as you can see, the function receives an ID an calls 'PromosBancos.aspx/CargarDatosModificacion' via ajax.
Well, that aspx contains some ASP controls, like textbox and stuff.
When I try to 'do the stuff' with that controls, I notice that I don't have access to them. So yes, it's the 'static' clause.
Obviously when I get rid of the 'static' keyword, I won't be able to make the ajax call work.
I tried making every control static, didn't work either.
So I'm in the middle of this trouble, and the question is: Is there ANY chance that I can access to the ASP Controls from a static method?
Or: Is there any way to achieve what I'm trying to do? (access ASP controls after clicking on a HTML element).

Related

How to select parts of an ajax response and put them into existing html elements

I'm trying to make a page where on the first instance, the page displays dynamic content from the DB only once without any Ajax. If the user clicks on a link, I would like to run an Ajax request, Retrieve the title, Date of the entry and the content form the database and replace the existing content in different parts of the page. I'd like to do this without repeating the whole page inside the PHP while loop since Jquery event handlers have been used on the content which is not being refreshed.
My idea was to use a javascript variable with a value of 0 on document load send it by Ajax and check its value in PHP. If the value is 0 I will set the value of the title, the Date and the content using the latest update in the DB, else I will set it according to the contents of the link.
I am wondering if Ajax can simplify my work.
My Javascript code
var statusOfClick =0;
var url = "post_this.php";
$.ajax({ //initial request once the document loads
url: url,
type: "POST",
data: "statusOfClick="+statusOfClick,
cache: false,
processData: false,
contentType: false
});
//change the source once the link is clicked
$("#blog-list ").on("click", "li", function(){
var getBlogByName = $(this).text();
var url = "post_this.php";
$.ajax({
url: url,
type: "POST",
data: "getBlogByName="+getBlogByName,
cache: false,
processData: false,
contentType: false,
success: function(){
/*how do I show parts of this response in different existing
html elements?*/
}
});
});
//change the source once the link is clicked
$("#blog-list ").on("click", "li", function(){clicked
var getBlogByName = $(this).text();
var url = "post_this.php";
$.ajax({
url: url,
type: "POST",
data: "getBlogByName="+getBlogByName,
success: function(response){
var d = $.parseJSON(response);
$("#title").html(d.title);
$("#date").val(d.date);
$("#content").html(d.content);
}
});
You can use this code. Encode the response in your PHP file using json_encode function. In your JS you can retrieve this values by parsing them into JSON using $.parseJSON function. Set the value of date, title and content in respective HTML elements. This is just an example please change it according to your requirement.

C# MVC Razor 5: location.href in an ajax call

I have a solution in my MVC project which allows me to show and/or hide a loading screen whenever I want to:
$("#divLoading").show();
$("#divLoading").hide();
This "divLoading" essentially contains the loading screen. Now this solution works fine most of the time; even if I want to use Ajax in order to show the loading screen when the script begins execution and hide it when the function is done. Something like:
$("#btnTreatData").click(function () {
$("#divLoading").show();
// Some stuff
$.ajax({
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("TreatValidationData", "Article")',
type: "POST",
data: JSON.stringify({ listOfCheckedData: listOfCheckedData }),
success: function (result) {
$("#tableControl").html(result);
$("#divLoading").hide();
}
});
}
This works fine. However, there is one specific edge-case where I can't get this to work properly.
Essentially, this project uses a plugin named EEPlus (http://epplus.codeplex.com/) in order to export data into an XLS file. It's very practical for the user because they simply click on the button, and there's no redirection involved; when the file is done, the user is prompted to download it by the browser itself.
Essentially, my export method does something like this:
public void ExportListUsingEPPlus(string filter, string type)
{
// A boat load of data processing and formatting that isn't relevant here
// Once the work is done:
// Write in an Excel file
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", $"attachment; filename={filename}.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
You will notice this method doesn't return anything. It doesn't need to; in the View itself, it is called like this:
<li class="separator"><input value="Export xls" class="add" name="btn_submit" id="btn_excel" type="button" onClick="location.href='#Url.Action("ExportListUsingEPPlus", "Article", new { filter = #ViewBag.CurrentFilter, type="TEST"})'"></li>
Which is okay... except that if I try to use a loading screen for this, because exporting data can take a long while:
function exportWithLoadingScreen()
{
$("#divLoading").show();
$.ajax({
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("ExportListUsingEPPlus", "Article", new { filter = #ViewBag.CurrentFilter, type = "TEST" })',
type: "POST"
}).complete(function (result) { $("#divLoading").hide();});
}
Ajax :
Doesn't proc a "success" event.
Doesn't proc a "failure" event.
Procs a "complete" event... but, of course, without location.href = '...', it doesn't actually do anything (the file is created in memory but the user is never prompted to download it).
If I try to use the same thing but caring about location.href, it procs the "complete" event far too early, possibly because it only cares when the redirection is complete, NOT when the method is done!
I really don't know what else I could try at this point, but it's so important to show a loading screen for this, because it really can take a long while.
Any ideas as to what else I could do? I'd appreciate it a lot!
EDIT: I'll be more precise and concise. This:
function exportWithLoadingScreen() {
$("#divLoading").show();
location.href = '#Url.Action("ExportListUsingEPPlus", "Article", new { filter = #ViewBag.CurrentFilter, type = "TEST" })';
$("#divLoading").hide();
}
Doesn't work, because all actions are simultaneous, so I have to use ajax. But this:
function exportWithLoadingScreen() {
$("#divLoading").show();
$.ajax({
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("ExportListUsingEPPlus", "Article", new { filter = #ViewBag.CurrentFilter, type = "TEST" })',
type: "POST"
}).complete(function (result) { $("#divLoading").hide(); })
};
Doesn't work either, because location.href is NOT executed (=> user is not prompted for download). But THIS:
function exportWithLoadingScreen() {
$("#divLoading").show();
$.ajax({
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("ExportListUsingEPPlus", "Article", new { filter = #ViewBag.CurrentFilter, type = "TEST" })',
type: "POST"
}).complete(function (result) { window.location.assign(result);})
};
Doesn't work, because the returned data is completely wrong (server error), because the ExportListUsingEPPlus method doesn't return anything.
EDIT EDIT: Edited question's title to refocus the question.
I think the confusion is made by the fact that you want to use an Ajax call, but also need to redirect the page.
Ajax is used to request data from the server back to the current page so that you can update the current page with the new data.
A redirect abandons the current page and replaces it with a new one entirely.
Here is another answer that explains it, with something that can simulate an Ajax request - but it still isn't an Ajax request if it is redirecting...
https://stackoverflow.com/a/9970672/4619012
You can get help from calling ajax events. Find it here https://api.jquery.com/Ajax_Events/

how to raise a C# event or function in javascript

I have a function in my login page an it access is protect like other C# function by default.
protected void MyFunction()
{
//do somthing
}
I want to raise it in JavaScript something like this
<script>
$.rise(MyFunction)
</script>
Someone said should use
__doPostBack(control, arg);
Or
<a .... onclick="TriggerPostBack('control', 'arg')" .. />
Or....
but all of this is for an ASP.NET object and if you use ASP.NET object it automatically generate callback and __doPostBack and everything you need.
Unfortunately I dont have an ASP.NET object and I use a simple HTML tag and want to raise a c# function by JavaScript manually.
is it possible? and the access of function what should be? and about the security? is it logical or illogical?
At the end I want to postback happen because I am familiar with jQuery AJAX and in this case I dont need it. I want postback happen.
Change your method to a static webmethod and try an jquery ajax post.
$.ajax({
type: "POST",
url: "YourPage.aspx/MyFunction",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
[WebMethod]
public static void MyFunction()
{
}

Codeigniter: Change languages on the fly (AJAX)

I am trying to work out how to change the languages on the fly using the Codeigniter Language System. So I made this ajax call which works but obviosly the values won't change until I reload the page unlease I somehow print out the values or set the variables in the function which is being called by AJAX ? What is the best way of doing this.
<script>
$(function(){
$('.lang-choices a').on('click' , function() {
var language = $(this).attr("data-lang");
$.ajax({
type: "POST",
url: js_site_url('langswitch/switchLanguage'),
data: "requestedLanguage=" + language,
cache: false,
success: function(html){
},
error:function(exception){alert('Exeption:'+exception);}
});
return false;
});
});
</script>
switchLanguage Function
public function switchLanguage()
{
$language = $this->input->post('requestedLanguage');
$this->session->set_userdata('site_lang', $language);
}
Your question is a little bit unclear so the assumption I'm making is that you're flipping a backend flag that changes the output from the server. Using that assumption, here's what I'd recommend in order of magnitude:
In your success handler, reload the page using window.location.reload(true). The true argument is essential since it makes a trip to the server to get new data. https://developer.mozilla.org/en-US/docs/Web/API/Location.reload
Your success handler seems to take html as an arg. I'm not sure if you're actually sending that based on your switchLanguage function or if that's leftover from copy+paste somewhere. If you are indeed getting HTML data and it's page data, I'd use the context option (http://api.jquery.com/jquery.ajax/) to filter down to the content of the document you're receiving then replace my page's content with this data
Here's an example of the latter:
$.ajax({
type: 'POST',
url: js_site_url( 'langswitch/switchLanguage' ),
data: 'requestedLanguage=' + language,
cache: false,
context: document.body,
success: function( html ){
// or similar
$( 'body' ).replaceWith( html );
},
error: function( exception ) {
alert( 'Exeption:' + exception );
}
});

Although I change the text of label it still returns initial value, how can I solve?

Although I assign the text to the label (lblDoc), for
<%FillRpt(rpt, lblDoc.Text , UserId);%>
lblDoc.Text is Label.
<asp:Label ID="lblDoc" runat="server" Text="Label" Visible="false"></asp:Label>
I changed the Text value but still it return "Label". How can I change it?
the case is below:
$.ajax({
type: "POST",
url: "FileManager.aspx/foo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#<%=lblDoc.ClientID%>").text(selectedPath);
<%FillRpt(rpt, lblDoc.Text , UserId);%>
},
});
Yes you are updating the client representation of a Label control on the client browser, but this value won't be read on the server code for two reasons:
When you do an HTML post on a page, only the form input fields are sent to the server, the Label control renders as a <span id="<ClientID>"> therefore the content of the span won't be sent as data to the server
Even if the span content tag were sent to the server, its value would be overridden with the Label value stored in the ViewState
Your code won't work the way you are trying for the above reasons, and (as far as I know) the ViewState field cannot be decrypted using JavaScript
As an alternative:
Keep changing the text of the span tag representing the Label
Add a hidden field, and when you change the Label text in JavaScript, replicate the same value in this hidden field, finally, in your server code use this value to change the Label.Text property
Why do you need the <% tags? You should just be able to do :
$("#lblDoc").text(selectedPath);
I solve the problem via using Web Method which return JSON data.
And after that
$.ajax({
type: "POST",
url:
data:
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//.........
});
},
error: function(msg) {
},
});
in the success part, I do what I want. For example I append some data to any tag such as
$("#stackOverflow").append(....)

Categories

Resources