File upload is not working properly in asp.net - asp.net

I am uploading a file from file upload control in asp.net. On that page there is a checkbox. User have to accept condition before he can upload the file. I am checking on code behind file that if the checkbox is not checked that show an alert message but the problem is that before calling that function the file is going to buffer whole on server and then the function is going called. But i want to to check that condition before temporary uploading of that file.
Below is my code that I am working with-
protected void btn_Upload_Click1(object sender, EventArgs e)
{
if (!chkBx_1.Checked )
{
dataclass.Message("Please accept all terms before uploading", this);
return;
}
else
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs("path");
}
}
}

Use some client side technology (javascript, silverlight, etc..) to check the checkbox first before submitting your form to the server.
If you want to be sure, you can recheck the checkbox on the serverside then.

Try to validate this checkbox with toolbox validator "RequiredFieldValidator".

It will be much easier for you to validate the checkbox in client side before continue.
Have look at this article about Related checkbox validation with JQuery. Also within the click function you can use event.preventDefault()
eg.
<input id="chbTest" cssClass="clChb" value="1" type="checkbox">
<script language="javascript">
(document).ready(function(){
$("#btnUpload").click(function(event){
if ($(".clChb").attr("checked") == false){
event.preventDefault();
alert('Please accept all terms before uploading ');
}
});
});
</script>
Also if you are not much familiar, you can have a look at this article about Using jQuery with ASP.NET which shows you how to include necessary script libraries.

Related

Braintree Drop-In UI in ASP.NET web form with submit button method is not called when clicked

I have created a simple payment form where contains fields that accept amount, the drop-in UI and the submit button.
<form id="form1" runat="server">
<div>
<label>Amount:</label>
<asp:TextBox ID="txtAmount" runat="server" />
</div>
<div id="dropin-container"></div>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>
braintree.setup("<%= this.ClientToken %>", "dropin", { container: "dropin-container" });
</script>
and the code behind
protected string ClientToken = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GenerateClientToken();
}
}
protected void GenerateClientToken()
{
var gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "merchant-id",
PublicKey = "public-key",
PrivateKey = "private-key"
};
this.ClientToken = gateway.ClientToken.generate();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
var gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "merchant-id",
PublicKey = "public-key",
PrivateKey = "private-key"
};
var request = new TransactionRequest
{
Amount = Convert.ToDecimal(this.txtAmount.Text),
PaymentMethodNonce = Request.Form["payment_method_nonce"]
};
Result<Transaction> result = gateway.Transaction.Sale(request);
}
After I load the page in the browser, I can see the form that accept amount and also the drop-in ui form which accept credit card and/or PayPal.
The issue is when I click Submit button, the method btnSubmit_Click doesn't get called. The page looks like it post back correctly but I cannot see any line of code within the btnSubmit_Click is executed.
I follow the instruction from this page:
https://www.braintreepayments.com/features/drop-in
But I really can't think of anything that I miss.
Anyone can help me with this issue would be very appreciated. Thank you so much.
Knott
I work at Braintree and can help you with this question.
Some background on what braintree.js is doing when you load the Drop-in on your page: it listens for form submissions, and when it detects one it will interrupt the form submit, communicate with Braintree to generate a nonce, and then run your callback if defined. What’s happening is that your .NET postback event is broadcasting a submit action – the same type of action that braintree.js interrupts in the first place.
As a workaround, you can try adding the following to your Page_Load code:
ClientScript.GetPostBackEventReference(this, string.Empty);
ClientScript.RegisterClientScriptBlock(this.GetType(), "PayEvent","<script>function PayEvent() {document.getElementById('__EVENTTARGET').value = '"+ btnSubmit.ClientID +"'; }</script>" );
btnSubmit.Attributes.Add("onClick", "PayEvent()");
Where btnSubmit is the ID of your button.
This should circumvent the submit interruption and allow your form to be submitted properly. In addition, this problem does not occur with our custom integration as an alternative.
Let us know if you have any further questions.
You just needed to put your transaction request code in a method and then call that sub on a post back rather than page load.
This way the auto submit won't interrupt with things.
Protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
GetClientToken();
} else {
Pay();
}
}
protected void Pay() {
PaymentMethodNonce = Request.Form["payment_method_nonce"]
//Build request string etc.
}
Brian,
Your solution above was supplied to me by PayPal support, but unfortunately, it doesn't solve the problem.
To be honest, it is this 'listening' (read: unreliable, 'clever code') to form submissions which is causing all the problems when one tries to integrate it in a Web Forms/UpdatePanel page - it really isn't designed for WebForms/UpdatePanels and requires all kinds of really messy code to make it work and synchronise properly. It is almost as if it was never designed for anything other than MVC or Java!
What would be a far better solution would be if we could attach a JavaScript call in OnClientClick of a button which synchronously calls BrainTree/PayPal via a JavaScript module hosted on PayPal which returns the nonce so that we can then do something with it. As it stands now, the Braintree/PayPal code intercepts a submit button (all buttons in WebForms are 'submits' by default, so this causes problems) and fires off a call asynchronously to get a nonce and at the same time, calls the button OnClick in the C# code. The net result is that the C# code runs before the Braintree/PayPal call returns and you can never synchronise the two.

Sharepoint "edit page" keeps loading due to certain webpart

I have a sharepoint test page. I inserted my webpart earlier before my development, but after a period of time now I find that when I click "edit page", the "loading" tag will run forever and I cannot edit my page.
Then I tried to type "?Contents=1" after my page url, delete the webpart and re-add it. When I tried to save my changes, the "saving" tag also runs forever.
Such issue only happens to my webpart. I tried to use other webparts and they works perfectly. Any one got some idea?
In your custom webpart code, you can understand if the page is in edit mode by the below code. Debug the code and try to understand the reasing of waiting.
By this way, you can modify your webpart for edit mode.
protected override void OnLoad(System.EventArgs e)
{
if (this.IsInEditMode)
{
}
}
private bool IsInEditMode
{
get
{
SPWebPartManager currentWebPartManager = (SPWebPartManager)WebPartManager.GetCurrentWebPartManager(this.Page);
return (((currentWebPartManager != null) && !base.IsStandalone) && currentWebPartManager.GetDisplayMode().AllowPageDesign);
}
}
OK,I find the reason. Since my webpart has an textbox validator and by default the textbox is hidden, when I click "edit page", the validator will be fired and prevent the editing. I put the following code in my page_load JavaScript and the issue is solved.
$(function () {
var rfv = document.getElementById("<%=rfvName.ClientID%>");
ValidatorEnable(rfv, false);
});

RenderControl in asp.net not getting the html i added into that control using JQuery

I am using a jQuery editor and when the user hits the submit button i put the content into asp.net Panel control as html and then when i render this Panel the html i added is not
retrieved.
function MoveData() {
var sHTML = $('#summernote_1').code();
// dvFrontPageHtml is asp.net Panel
$('[id*=dvFrontPageHtml]').html(sHTML);
setTimeout(function () {
javascript: __doPostBack('ctl00$ctl00$ContentPlaceHolderBody$ContentPlaceHolderBody$lnkSave', '');
}, 10000);
return false;
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
dvFrontPageHtml.RenderControl(htmlWriter);
string Message = sb.ToString();
The message does not returning the html added.
I dont want to use jQuery ajax call as of now.
Any suggestions
without seeing all the relevant code its hard to pinpoint the problem.
but im pretty sure you are trying to find an ASP.net control by its serverside ID from clientside.
dvFrontPageHtml is the Controls ID by which asp.net identifies it, and unless you explicitly tell ASP.Net otherwise, it will generate a different ID for the control to be used by scripts at clientside
you need to retrieve the panel's clientside ID thats being generated for it by asp.net
you do it by a preprocessor directive <%=dvFrontPageHtml.ClientID%>:
$('[id*=<%=dvFrontPageHtml.ClientID%>]').html(sHTML);
alternatively, if you want the clientside ID to be same as the serverside ID, you can set the control's attribute ClientIDMode="Static".
UPDATE:
from your comment it seems the problem is elsewhere. what comes to mind, is that RenderControl() takes the control as it was when sent to the client in the Response. but the control is not being submitted to the server in next Request, so you will not be able to retrieve its altered html.
what you can do as a workaround, is hook into ASP.NET's build in postback mechanism, and submit the panel's html as a custom event argument:
for the example, lets assume this is our html:
<asp:Panel ID="dvFrontPageHtml" runat="server" ClientIDMode="Static">test</asp:Panel>
<asp:Button ID="BT_Test" runat="server" Text="Button"></asp:Button>
this will be our javascript:
$(function(){
// add custom event handler for the submit button
$("#<%=BT_Test.ClientID%>").click(function (ev) {
//prevent the default behavior and stop it from submitting the form
ev.preventDefault();
//alter the panels html as you require
var sHTML = $('#summernote_1').code();
$('[id*=dvFrontPageHtml]').html(sHTML);
//cause a postback manually, with target = BTCLICK and argument = panel's html
__doPostBack('BTCLICK', $('[id*=dvFrontPageHtml]').outerHTML());
});
});
and here we capture the postback on serverside:
//we monitor page load
protected void Page_Load(object sender, EventArgs e)
{
string Message;
//check if its a postback
if (IsPostBack)
{
//monitor for our custom target "BTCLICK"
if (Request.Form["__EVENTTARGET"].CompareTo("BTCLICK") == 0)
{
// retrieve the panels html from the event argument
Message = Request.Form["__EVENTARGUMENT"];
}
}
}

File upload control in ASP.NET

i am using file upload control in ASP.NET for uploading images.
In my form there are two buttons.one for assigning criteria which redirects to other form and other for submitting form.
After assigning criteria only the user has to use submit button.
My problem is when is upload image and click on AssignCriteria button and return back to original page,the upload control is getting blank.
How to keep that upload image control value in that textbox even if we redirected to other page and come back.
<asp:FileUpload runat="server" ID="uploadStatement" />
<asp:Button runat="server" Text="Upload" OnClick="cmdUpload_Click" />
Next code uploads selected file to Temp folder on the server, in my case - parses it and deletes the file.
protected void cmdUpload_Click(object sender, EventArgs e)
{
var fileName = Server.MapPath(Path.Combine("Temp", String.Concat(Guid.NewGuid().ToString(), Path.GetExtension(uploadStatement.FileName))));
try
{
uploadStatement.SaveAs(fileName);
// parse file
}
finally
{
File.Delete(fileName);
}
}
Since any manipulation with the "input type='file'" element is a serious security threat I am afraid there is no way to do this.
Have you considered using of some AJAX overlay "dialog"?

adding comments like facebook with ASP.NET

I'm developing an blog using ASP.NET, and I want that the user can be able to add comments.
So I want to implement the idea of facebook on adding comments.
The comment will be stored in the database, so I will be able to load it with the page if the user goes to another web page.
You have any idea how can I do this thing ( Ajax, Javascript, jQuery, Ajax Toolkit ) ?
EDIT:
I found this :
<body>
<form id="form1" runat="server">
<p>
<textarea id="textArea"></textarea>
</p>
<input type="submit" value="Commenter"/>
<br />
</form>
<p>Add some Test to the page</p>
</body>
and script.js :
window.onload = initAll;
function initAll() {
document.getElementsByTagName("form")[0].onsubmit = addNode;
}
function addNode() {
var inText = document.getElementById("textArea").value;
var newText = document.createTextNode(inText);
var newGraf = document.createElement("p");
newGraf.appendChild(newText);
var docBody = document.getElementsByTagName("body")[0];
docBody.appendChild(newGraf);
return false;
}
But how can I save the comment in the database, because an input button can't do this !
You don't necessarily need to use JavaScript to do this, although if you wish to do this asynchronously to provide a more responsive user experience then you will need JavaScript.
Using ASP.NET web forms, there are a number of ways this could be set up on the server side. You could use
Page methods
ASMX web services
WCF services
And call them using JavaScript from the client side. Inside of the server side code is where you will connect to the database, perform your CRUD operation and return a response back to the client that made the AJAX call.
A note on security - you'll want to sanitise the comments and mitigate SQL injection, XSS, XSRF and other types of injection attacks. The Anti-XSS library (soon to be superceded by the Web Protection library) is a good tool to leverage to do this and offers a better approach to encoding than the standard encoding in ASP.NET
Generally, if you are using GridView to display those blog post, simply add a template field into the Gridview. Inside the template filed, you put a Textbox and a Button.
When user click on the button, use your code behind to find the postID, and textbox, and save it to database, and then remember to bind the data to the gridview again.
Here is some sample code.
protected void btnBuy_Click(object sender, ImageClickEventArgs e)
{
ImageButton btnBuy = (ImageButton)sender; //Find which button is clicked.
//If that is a button, use Button btnBuy = (Button)Sender;
GridViewRow row = (GridViewRow)btnBuy.NamingContainer; //Find which gridview row //containes the clicked button
Label lblPostID = (Label)row.FindControl("lblPostID"); //Find the post ID
TextBox txtComment = (TextBox)row.FindControl("txtComments"); //Find the textbox
//Save the data to database.
//Put your code here.
//Bind the gridview with the data source which got some new data.
GridView1.DataSource = yourDataSource;
GridView1.DataBind();
}

Resources