React/javascript component to send data back to aspx - javascript

I've a legacy ASP.NET application, which I'm trying to modernize. I've a page
MyPage.aspx, and its codebehind MyPage.aspx.cs
I've replaced a custom user control (which does a fileupload) with a custom react component. The react component is working as expected. The old ascx usercontrol had an event handler which is defined in 'MyPage.aspx.cs'as follows.
protected void asyncFile_FileUploaded(object sender, FileUploadedEventArgs e)
//logic to set the uploaded file's name etc for saving.
}
Nowthat the custom control is replaced with an empty DIV, where the react component is being mounted, I'm left with no option to call my C# logic in the 'MyPage.aspx.cs' codebehind file.
I've created a 'CreateProperty.aspx.js' file which is responsible of initializing my react component inside the .aspx page, and below is the contents of this file.
$(document).ready(function () {
if ($('#Myupload').length) {
ReactDOM.render(
<Upload id="pictureupload2"
onChange={onChange}
setBusyState={onBusy}
onUploadSucceeded={onUploadSucceeded}
/>,
document.getElementById("Myupload")
);
}
});
function onChange(e) {
console.log(e);
}
function onBusy(e) {
console.log(e);
}
function onUploadSucceeded(e) {
console.log(e);
}
Once the react component has done the uploading, it calls the function onUploadSucceeded() with my required parameters. But how will I pass that value back to my MyPage.aspx.cs file ?
Please help.

Drop in a standard asp.net button on the form.
Move the code you have/had for the previous event into that button code stub
eg:
protected void asyncFile_FileUploaded(object sender, FileUploadedEventArgs e)
//logic to set the uploaded file's name etc for saving.
}
So, move the above code to the button (style="display:none) to hide it.
AND OF COURSE don't copy the event stub code!!!.
Now, in your js function, do whatever and simply "click" on that button.
The bonus here is you get the badly needed post back when the client side js/ajax runs.
So, you have this:
function onUploadSucceeded(e) {
console.log(e);
document.getElementById('<%= btnOkUpLoad.ClientID %>').click();
So, the above is nice. I mean you could do a js __DoPostBack(); in js, but then you have to pass some parameters, and then client side in the on-load page event, detect the parameters (a pain to wrire up).
So, anytime I want to run code behind from js? Just drop in a asp button, write the code stub for that button, and then client side, use the above ".click()" to run that code. As noted, in MOST cases you want a post back anyway - which is what a asp.net button does for you.
Edit: now I said we want a post back in most cases? Well, I mean when we are all said and done - and thus this button click makes sense. We certainly don't want needless post backs - but when you do, and when you want to run+call a code stub, the this button trick is nice. Just use style="display:none" to hide it from view - but js code can still use the .click() to run (click) the button for you))

Related

JavaScript PopUp appears only ONCE on a page per user in ASP.NET

This is something I already know the answer to but I want to come up with a better way. I have a dropdown within a gridview. Within the method that populates the dropdown data I'm adding an an "onchange" attribute to the dropdown. The onchange calls a javascript function that is then used to fire a popup based on what the user selects on the dropdown.
My issues is I want the popup to display only once within that current page for that user. The easiest answer is to use JavaScript sessionStorage to store some dummy value that is checked before the javascript popup code is run and then set afterwards.
The problem I'm having is that I then have to manage the storage by either clearing the storage when the user goes to another page by attaching storage.clear to all the buttons dealing with moving to another page.
Is there a way that I can clear the storage after the person moves to another page other than the page they are on. BTW the dropdowns and javascript are all located within an ASP.NET custom control. That custom control is loaded within several pages, therefore I want the logic to be isolated within the custom control so that I don't have to make changes to every page that uses the control and for modularity.
You can in the page on load, just set a global js var to the page like this:
protected void Page_Load(object sender, EventArgs e)
{
string script;
if (IsPostBack)
{
script = "var isPostBack = true;";
}
else
{
script = "var isPostBack = false;";
}
Page.ClientScript.RegisterStartupScript(GetType(), "IsPostBack", script, true);
}
So, now in your js code, you can use isPostBack as a simple true/false var.

Trigger Apache Velocity #set Parameter using a button (HTML / JS)

Is it possible to trigger a Velocity Template Language #set value to parameter via a button?
I am trying to combine HTML, JS and Velocity doing the following:
#set($ld=$pageParameters.Work_Item_Link_Direction.values)
<button id="demo2">up</button>
<script>
document.getElementById('demo2').onclick = function() {
#set( $ld = "up" )
alert("button2 was clicked");
};
</script>
The part, however, which doesn't work in this code is:
#set ( $ld = "up")
as it isn't pure JavaScript.
Any hints or ideas how I can combine anyway this "#set value to parameter" as function onclick to the button? I am working inside the application Polarion ALM.
Or is there any other approach how I can set a value to a (page) parameter using velocity and using a Button?
There is a little misconception, here:
the Velocity Template Language code is evaluated at the time the page is sent by the HTTP server, on the server itself.
the Javascript code is evaluated once the page is loaded, in the browser.
So what you ask for doesn't really make sense.
What you can do, however, is trigger an ajax call from inside your javascript handler, which can set some value inside the session, return some value to the success ajax handler, etc.

How do I pass in postback argument from JS to VB?

I am trying to pass in an image from an image editor to a function in VB. I have it setup as the following:
JS
var canvas = document.getElementById("canvas_minipaint");
var img = canvas.toDataURL("image/jpeg");
__doPostBack('SaveImage', img);
ASPX
<asp:LinkButton ID="SaveImage" runat="server" Visible="true"></asp:LinkButton>
VB
Private Sub SaveImage_Click(sender As Object, e As EventArgs) Handles SaveImage.Click
Call GetSession()
End Sub
When I click the SaveImage button right now i get the following error:
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
How do I register the onClick for the button for the validator? Or am I missing something else?
Turn off event validation for this page. You can turn it off at page level by adding
Page EnableEventValidation="false"
to the top of your .aspx page. I would recommend doing that in this case, since you are doing a manual postback using JavaScript. It is not possible to turn it off for individual controls.
EDIT:
You could always store the value of the image in a hidden field, and that would prevent the need to disable event validation. You'd need a way of storing the image data (base64 string maybe?) in the field, but it would work.
I would suggest not disabling the EventValidation to avoid malicious users to mess with the form. You could store the data in an input hidden or override the page event and handle it.
protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
{
if (sourceControl is yourControl)
{
//sanitize data
}
}

Server side alert disturbs page styling

I needed to show a message on web page. I'm using ASP.Net and C#. I added below code in the back-end code to show message to the user
protected void btnRenew_Click(object sender, ImageClickEventArgs e)
{
//other code removed for clarity on where and how this alert is triggered
if (newExpiryDate.Date == memberDetails.ExpiryDate.Date)
{
Response.Write("<script>alert('Invalid renewal date');</script>");
}
}
This works fine as expected on the event call. But, the moment I click OK button on the alert message, the font-size of the text increases. It looks like somehow this alert message is disturbing my styles on the page.
Does anyone know a safe method to display alert from ASP.Net code behind page?
It is hard to tell what is causing the font shift based on what you posted, but your design can be vastly improved by 1. not making a server call just to validate a date, and 2. not using alert() which locks the whole browser until someone clicks "ok".
You could change your approach to set a few variables in javascript on page load, and then trigger a function on say change of your input or even on button click. your check function could look something like this
_memberExpiryDate = new Date('#memberDetails.ExpiryDate.Date'); // or whatever the notation is to write out server variable here
function validate() {
if (new Date($('#myDateInput').value()) >= _memberExpiryDate.getTime()))
$('#invalidDateLabel').show();
}
this way you're not making unnecessary postbacks, validation can autocorrect as users adjust dates, and there are no alerts in your face.
you can also use a library such as Toastr to show a more graceful message which disappears after a few seconds. but ideally you want to show something right next to the input field like asp.net date validator even
toastr.error('date is expired');
Also you could just use the asp.net range Validator.
See if
<script>setTimeout(function(){alert('Invalid renewal date');},1000);</script>
fixes your issue
Using ClientRegisterScriptBlock
protected void btnRenew_Click(object sender, ImageClickEventArgs e)
{
//other code removed for clarity on where and how this alert is triggered
if (newExpiryDate.Date == memberDetails.ExpiryDate.Date)
{
ClientScript.RegisterClientScriptBlock
("".GetType(), "s", "<script>alert('Invalid renewal date');</script>");
}
}
This renders the script in the HEAD section

Need to call a Javascript function from .aspx (VB.net) page any time a postback happens

I have a large .aspx page, with multiple server controls. And, there is also a JavaScript file referenced by this .aspx page. I want to have a JavaScript function within this existing .js file, that will get called before any postback that happens to the server.
[note: I have seen another post that mention how to do this in JQuery ( How to capture submit event using jQuery in an ASP.NET application? ), but I would like that to be done through the existing JavaScript file, rather than using a new technology like JQuery]
[Edited] Solution of using OnSubmit handler will not work for me...because it will not get called for postbacks that get triggered by server controls.
You need something like this:
/*
usually there is only one form in asp.net, but if you know you can have
more than one, you can get main form with document.getElementById
*/
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener) {
form.addEventListener('submit', functionThatShouldBeCalledBeforeSubmit, false);
} else if (form.attachEvent) {
form.attachEvent('onsubmit', functionThatShouldBeCalledBeforeSubmit);
}
onsubmit event will rise any time form is submitted. No matter how.
More details about attaching events with JS: https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener

Categories