VB.net success and refresh code? - javascript

I have a page in my site that has 5 different textboxes to add different things to my database. I would like each one to be able to have a success code tied to it, but also be able to refresh the page. I use Response.Write("<script>alert(" & "'Image Title added successfully'" & ")</script>") to show the message, but when I add Response.Redirect("AddToPicklist.aspx") to it, the success message doesn't display anymore. Is there an easier way to do this is ASP.net?
<tr><td class="title">Image</td></tr>
<tr><td>Image Title: </td></tr>
<tr><td><asp:TextBox ID="txtImageTitle" runat="server"></asp:TextBox></td></tr>
<tr><td><asp:Button ID="btnSubmitImage" runat="server" Text="Submit" /></td></tr>
</table><br />
Protected Sub btnSubmitImage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmitImage.Click
**insert code is here but it's not relevant so I'm omitting it**
Response.Write("<script>alert(" & "'Image Title added successfully'" & ")</script>")
Response.Redirect("AddToPicklist.aspx")

You are redirecting within the same request, therefore the javascript you wish to output will never be rendered.
1 solution would be to pass a querystring to your next page like:
Response.Redirect("AddToPicklist.aspx?alert=titleadded")
Then on AddToPicklist.aspx do:
If Request.QueryString("alert") = "titleadded" Then
Response.Write("<script>alert(" & "'Image Title added successfully'" & ")</script>")
End If
Alternatively you could redirect to the page via javascript after the alert, but this would be bad for users who do not have javascript enabled.
On a side note, look into the use of ClientScriptManager.RegisterStartupScript for outputting javascript, rather than Response.Write
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

The Redirect will be making the page (or another page - not sure what your pages are called) reload from scratch and so the click event will not be entered again and the <script> will not be inserted.
I would advise against producing messages on the client by using Response.Write. At the very least use registerclientscriptblock eg
RegisterClientScriptBlock("showSaveMessage", _
"<script language=""JavaScript""> _
alert('Your changes have been saved.'); _
</script>")
(from MSDN)
But I would instead consider using a WebService to write to your DB. And then you won't have to have a full postback.

I am going to use Response.Write("<script type='text/javascript'>{ alert('Image Title added successfully'); document.location.href = 'AddToPickList.aspx'; }</script>")

Related

Java script values set into index of asp drop down

I have asp.net drop down list but I want to load previous classic asp page value into index of the drop down list using Java script.
I can able to take the previous page value with use of Java script.but I am unable set into asp drop down index when page is loaded. Drop down list showing only data from data base not from Java script value.
Protected void page_load()
{
this.BindCountrydropdown();
}
Protected void BindCountrydropdown()
{
/*I have written stored procedure to load values using Data adapter and data table*/
this.ddlCountry.DataTextField=“Countryname”;
this.ddlCountry.DataValueField=“CoubtryID”;
this.ddlCountry.Databind();
}
In .aspx page. Java script:
<script>
function loadpreviouspagevalues()
{
document.getElementById(“ddlCountry”).value=window.opener.parent.document.getElementById(“CountryName”).value;
}
</script>
<body onload =“ loadpreviouspagevalues()”>
<asp:DropDownList ID=“ddlCountry” runat =“server”> </asp:DropDownList>
...
Country name should loaded into ddlCountry index values.
First of all, there are multiple errors just in your javascript function.
function loadpreviouspagevalues(){
document // should not be a capital "D"
.getElementById // No Extra "." should go after this
("ddlCountry").value = window.opener.parent.document.getElementById("CountryName").value;
// I am also skeptical about the inverted commas that you have used here. These are not surely correct
}
Change these and test. Also, when dealing with JavaScript, it is crucial to check browser console to see if any error is there and resolve it accordingly.
I see, you are fetching the value from another page, I would suggest you first validate if the value is properly being returned or not. If it is, then there is the syntactical issue that you need to fix in JavaScript.

Upload a file to a server using ASP.NET and C#

I am new to forms and am trying to get an understanding of what is going on. I have looked at lots of questions and tutorials, but feel unclear on certain points.
So far I have created the following form in an aspx page:
<form id="uploadbanner" enctype="multipart/form-data" method="post" action="#">
<span class="txtSmallGrey fl" style="display:block; width:200px; margin:15px; margin-bottom:2px">
<%= oUtils.GetContentText("Collect_Config_upload_sound") %>
</span>
<input type="file" name="SoundFile" id="SoundFile" style="margin:15px; margin-bottom:2px">
<input type="submit" value="Upload" id="submit" style="float:left; margin-left:245px; margin-top:1px; height:20px;">
</form>
and I have the following script at the top of the page:
<%
if(Request.Form["SoundFile"] != "")
{
HttpPostedFile file = Request.Files["SoundFile"];
string fname = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
}
%>
I have a reasonable understanding of AJAX so some of this seems familiar to me.
Now to explain what I understand:
The form is declared and given the id of 'uploadbanner'. As I am transferring a file I have to include 'enctype...' I am posting as it is more secure and more flexible.
The action term tells the form where to post to. In this case I have put the C# code at the top of the page so do not need to include an asp.net page address to process this. If I did, I would include an asp.net page, in the same way as I would for AJAX (I think?).
Anything with an input tag inside the form tags will be posted in the form, and will send the name and value.
When the submit button is pressed, the form will be submitted to the the server side code for processing. So far I feel I understand what is going on.
Now the parts I feel less clear about,
Is it the case the when the 'submit' button is pressed, the C# code
at the top of the page will be activated, and so if the field was
blank it would not do anything?
And if the button was pressed multiple times, would the form be
submitted multiple times?
If so, then this is much the same way as AJAX?, and the file will
simply be passed to the C# code, from where I can do what I need with
it?
My final questions is, can I submit the form using an alternate
method to the submit button, eg can I make a normal JavaScript button
and tell it to submit the form?
Is it the case the when the 'submit' button is pressed, the C# code at the top of the page will be activated, and so if the field was blank it would not do anything?
Yes, Every time your page loads it will run the C# code, One would assume that if you submit the form it will check the posted form data. It's probably best to check HTTP headers.
And if the button was pressed multiple times, would the form be submitted multiple times?
Yes, the form will be submitted multiple times.
If so, then this is much the same way as AJAX?, and the file will simply be passed to the C# code, from where I can do what I need with it?
It's similar in the sense of HTTP requests but your posting to the page with a file attached and then C# checks with the page has file attached by running the Request.Form and then Request.Files and Posts to the server.
My final questions is, can I submit the form using an alternate method to the submit button, eg can I make a normal JavaScript button and tell it to submit the form?
What do you mean by a normal JavaScript button? You don't have to use a submit button. As long as your passing in a file and the page is loaded, the code will still run. I have approach where as i post to a HTTPHandler. Code snippet below:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
HttpPostedFile postedFile = context.Request.Files["Filedata"];
string filename = postedFile.FileName;
var Extension = filename.Substring(filename.LastIndexOf('.')
+ 1).ToLower();
string savepath =HttpContext.Current.Server.MapPath("/images/profile/");
postedFile.SaveAs(savepath + #"\" + user.uid + filename);
}
So when submitting i point to the HttpHandler.ashx which is a class that implements the IHttpHandler interface, Which in turn gets the current context.

calling a method with jsf 2.0 ajax library

I am working on an application where users will be evaluating a piece of art and filling out a review form as they go along. They may spend a substantial amount of time on the form, so I want to save it automatically for the user, say every 5 minutes. I was hoping I could use javascript and set a timer for the 5 minutes and then have it basically execute the entire form via ajax and I could save the data to the database in case the user gets disconnected, etc. Unfortunately I cannot seem to find any way to do this. Getting the model updated with the data is not a problem, but I can't figure out how to get it to invoke the method (similar to how the action normally would when it was submitted.) I don't want or need it to re-render anything, just let me call a method to save the data. How can I do this?
Problems implementing the solution
I tried implementing the solution of the hidden command link but I'm getting some very strange behavior. I am not sure what is causing this. First, some background on the implementation. Form #1 creates a bean (None scoped) and puts it into the flash, then redirects to Form #2. Form #2 is the big form I was writing about, where I want to implement the auto-save. Form #2 has a ViewScoped bean. In the PostConstruct for this bean, it retrieves the value from flash, and populates a property field. So far so good. This works perfectly without the javascript. I can press the command button to submit the form, and all is well. However, when I introduce the javascript, when it executes I get a null pointer exception from the variable that should have been populated from the flash by the PostConstruct. How is this javascript interfering with that? Once I have populated the property of view scoped bean with the object, it should not matter if its removed from flash scope, right? FYI if I remove ONLY the javascript code and leave everything else it goes back to working fine when I press the button to submit.
Form #1
<h:form>
... bunch of form objects ...
<h:commandButton "Start New" action="#{someRequestScopedBean.someMethod"/>
</h:form>
code for someRequestScopedBean.Method:
public String someMethod() {
// bunch of logic here
FacesContext.getCurrentInstance()
.getExternalContext()
.getFlash()
.put("myFlashObj", myFlashObj);
return "form2?faces-redirect=true";
}
view scoped bean used in form 2:
#ManagedBean
#ViewScoped
public class someViewScopedBean {
//bunch of properties here
#PostConstruct
public void initialize() {
this.myObject = (MyObject) FacesContext.getCurrentInstance()
.getExternalContext()
.getFlash()
.get("myFlashObject");
public void saveDraft() {
// save to database
}
}
Form 2 page:
<h:outputScript library="javax.faces" name="jsf.js"/>
<h:form id="myForm">
... whole bunch of fields here ...
... real button for user to submit ...
<h:commandButton value="Submit myForm"
action="#{someViewScopedBean.save}" />
... hidden button for auto-save by javascript ...
<h:commandLink id="hiddenSaveDraft" style="display: none;"
action="#{someViewScopedBean.saveDraft}" >
<f:ajax execute="#form" />
</h:commandLink>
<script>
function saveDraft() {
document.getElementById('qForm:hiddenSaveDraft').onclick();
window.setTimeout('saveDraft()',15000);
}
saveDraft();
</script>
</h:form>
Since you wrote down Javascript as one of your tags i'm going to assume you incorporate Client side Javascript code in your app.
First of all use a hidden <h:commandButton/> or a hidden <h:inputText/> ( I use the latter in cases where I need to hold some information regarding a certain variable)
In the form you are submitting add one of these:
<h:commandButton style="display:none" id="clickme">
<f:ajax execute="#form">
</h:commandButton>
<h:inputText style="display:none" id="changeme">
<f:ajax execute="#form">
</h:inputText>
In your Javascript code add this code to either click or change:
setInterval(function() {
document.getElementById("clickme").onclick();
}, 3000); // update every 3 seconds
setInterval(function() {
document.getElementById("changeme").onchange();
}, 3000); // update every 3 seconds
Both will work fine. Just make sure they are within the form you are updating.
I figured out the final solution, and the cause of problems I had implementing it the first time around. It had to do with WHEN the javascript was being fired. The script code was being fired at the exact point I placed the <script></script> block, which was before the page was completely loaded and probably before the DOM was complete. This was causing all kinds of nasty, including duplicate invocations of #PostConstruct.
I fixed it by using a javascript event listener to fire when the page was completely loaded. This is important because I am using facelets templating, and I didn't have access to the <h:body onload= attribute. The listener is a useful and elegant solution. The script block can be placed anywhere in the page. Here is what the script block looks like:
<script>
function saveDraft() {
document.getElementById('qForm:saveDraft').onclick();
window.setTimeout(saveDraft,300000);
}
function initSaveTimer(e) {
window.setTimeout(saveDraft,300000);
}
this.addEventListener("load",initSaveTimer,true);
</script>
This will invoke the hidden button every 5 minutes to save the form.

a4j:param not invoking my javascript pointed to by value attribute

I am open to a different way to do this, but what I have seems like it should work from the documentation for RichFaces4 and JSF2.
The user flow is like this:
1) There is a 'Check Out' document link implemented with h:outputLink
2) The user clicks it and gets prompted with a dialog to enter check out comments implemented with rich:popupPanel
3) The user enters comments and clicks 'Continue' Button on the rich:popupPanel implemented with h:link (tried h:commandLink and a4j:commandLink also)
4) A new window pops up with the contents set to the h:link outcome attribute
In my broken case, everything works except when I pass a parameter from h:link
with a4j:param, whose value attribute does not resolve the javascript it points to correctly.
<h:outputLink id="promptForCommentsLink"
onclick="#{rich:component('commentsDlg')}.show();return false;"
value="#"> Check Out </h:outputLink>
<rich:popupPanel id="commentsDlg" modal="true">
<h:inputTextarea id="commentsId"/>
<h:link id="continueLink"
outcome="editorPage" <!-- editor for making changes to document -->
target="_blank" <!-- open in it;s own indow -->
value="Continue Check Out"
onclick="#{rich:component('commentsDlg')}.hide();">
<!-- these params get assignd to backing bean properties -->
<a4j:param name="dataId"
value="#{ithRow.id}" assignTo="#{myController.dataId}"/>
<a4j:param name="checkedOut"
value="true" assignTo="#{myController.checkedOut}"/>
<!-- this one is broken. assigns chars 'document.getElementById('..
to #{myController.checkOutComment} -->
<a4j:param name="checkOutComment"
assignTo="#{myController.checkOutComment}"
noEscape="true"
value="document.getElementById('myForm:dataTable:0:commentsId').value"
/>
</h:link>
</rich:popupPanel>
I was thinking maybe
document.getElementById('myForm:dataTable:0:commentsId').value
didn't point to what I typed into the textarea, but by putting another button on the dlg and pointing it's onclick to the same element id, it did indeed alert me with what it typed.
When I stop on the server side view scoped myController.setCheckOutComment(String s) method, it gets passed the string "document.getElementById('myForm:dataTable:0:commentsId').value"
According to RF4 documentation:
The a4j:param tag can be used with non-Ajax components in addition to Ajax components. This includes components which are working through the GET request, such as the h:link
and
Variables from JavaScript functions can be used for the value attribute. In such an implementation, the noEscape attribute should be set to true. Using noEscape="true", the value attribute can contain any JavaScript expression or JavaScript function invocation, and the result will be sent to the server as the value attribute.
Since I seem to be playing by the jsf/rf4 rules, I thought this would be okay.
One thing to note, if I use a4j:commandLink instead of h:link, it does indeed
send the result of javascript evaluated, however, that breaks the opening in its own window
and a few other issues.
Any thoughts on what might be happening, or even a better way to do this?
You could use a a4j:jsFunction with the parameters you need. Then call that function from the onclick in the h:link tag like setParams(#{ithRow.id}, true). Problem remain that you can't pass the value as a parameter to the javascript function. You could though use 'execute' to save the value of the inputArea to a backing bean and let the backend handle the value.
So yes, I would do it differently. I think you could handle the two other params at the backend and I would use 'execute' to store the value of the inputArea.
MAG,
Milo van der Zee

pass javascript value to asp.net function

the question says it all : i have a linkbutton to which i pass through CommandArgument a value and i need that value to be a javascript value. Thanks!
Edit :
here is my linkbutton tag :
< asp:linkbutton id="prevBut"
runat="server" OnCommand="load_com"
CommandArgument=to_place_javascript_string
Text="previous" />
and the function :
public void load_com(object sender, CommandEventArgs e)
{ //get the string from e and search through the database for something }
i want to pass the name of a photo that is stored in a variable $.galleria.current.
You need to stop for a moment and think about what the LinkButton is actually doing. It's not magic. It's just posting the form for you.
As such, you can...
define an onsubmit handler to stuff that javascript value into a hidden form field
or, replace that LinkButton with a simple <a onclick="dostuff()"> pointing at a function that stuffs your value into a hidden form field and submits the form
or, replace that LinkButton with a simple <a onclick="dostuff()"> pointing at a function that constructs a URL containing ?myvalue=whatever and redirects to it.
There's no reason you need to involve ASP:LinkButton in any of it. If the built-in ASP.NET controls aren't doing what you want. All you need to do is stop using them.
(Incidentally, you'll have a much happier and more productive career in the .NET world if you stop using Microsoft's Rich Controls in favor of their HTML equivalents. Those things are there so that non-programmers can drag/drop their way to unmaintainable websites. Since you're here, we can assume you're not a non-programmer, and are therefore smart enough to ignore the marketing portions of ASP.NET and use the good stuff directly.)
Are you looking to place a string of javascript code in the command argument or a value which can be accessed via javascript?
If you need a value to be accessible via javascript you could put the command argument value in an attribute of the linkbutton <a href="javascript:void(null)" commandArg="value" >Link Text</a> this would make "commandArg" available via jQuery like $('#linkID').attr('commandArg') . You could obviously name that attrubute whatever you need to.

Categories