How to make FileUpload control upload file right after clicking 'Browse'? - c#

Untill now, I've been using 2 controls (FileUpload and additional button).
After file was chosen in a fileUpload control, user had to accept his choice by pressing save button.
Here's button's code:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("~/file.jpg"));
Label1.Text = Server.MapPath("~/file.jpg");
Image1.ImageUrl = "file.jpg";
}
}
I'm wondering whether there is a way to avoid using that button, so the FileUpload control's button would do the additional button's job.

The FileUpload control renders an <input type="file> in the browser. You can use the javascript change event to trigger the upload.
First make sure you have a load event handler registered in the body of your page:
<body onload="body_onload()">
And add this code inside your event handler:
<script type="text/javascript">
function body_onload()
{
...
$get('<%=FileUpload.ClientID%>').onchange = function() {
$get('<%=this.Page.Form.ClientID%>').submit();
};
}
</script>
Or to do this using pure jQuery, place this in the head of your page (if you don't already have jQuery included):
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
Then use this code to bind to the event (replace #fileUpload1 and #form1 with the id's of your FileUpload and Form elements, respectively):
<script type="text/javascript">
$(document).ready(function() {
$("#fileUpload1").change(function() {
$("#form1").submit();
});
});
</script>

Related

Handling multiple UserControls

I have a webpage Containing UserControl repeated 2 times with same functionality. I want to disable the textbox in first UserControl but it is getting disabled in 2nd UserControl.
How to check this?
<script type="text/javascript">
function confirmCallBackFn(arg)
{
if (arg == true)
{
$find('<%= txtOne.ClientID %>').disable();
}
}
Method 1 - If the event is triggered by a control in the parent form
In the user control, you can define a property that returns the ID of the TextBox:
public string TextBoxID
{
get { return txtOne.ClientID; }
}
If your form contains two instances of the user control, ctrl1 and ctrl2, you can target a specific one like this:
document.getElementById('<%= ctrl1.TextBoxID %>').disabled = true;
Note: In the user control, make sure that you don't use ClientIDMode="Static" for the inner controls.
Method 2 - If the event is triggered by an inner control of the user control
If your user control contains the following markup:
<asp:CheckBox ID="chk1" runat="server" />
<asp:TextBox ID="txtOne" runat="server" />
you can add Javascript event handlers to the CheckBox in the Page_Load method of the user control:
protected void Page_Load(object sender, EventArgs e)
{
string js = string.Format("txtBoxID = '{0}';", txtOne.ClientID);
chk1.Attributes.Add("onmousedown", js);
chk1.Attributes.Add("onkeydown", js);
}
These event handlers set the value for a txtBoxID variable that you can define and use in your Javascript block:
<script type="text/javascript">
var txtBoxID;
function confirmCallBackFn(arg) {
if (arg == true) {
document.getElementById(txtBoxID).disabled = true;
}
}
</script>
This method assumes that there is no postback during the process. If a postback occurs, we may have to modify that method and register a script in the event handler in code-behind.

Setting ASP.NET Button attributes client side and read attribute value server side

How can I retrieve a Button custom attribute after the attribute value has been changed using javascript?
Example:
Asp file
<asp:Button ID="Button1" runat="server" Text="Button1" />
<asp:Button ID="Button2" runat="server" Text="Button2" OnClick="Button2_Click" />
<script type="text/javascript">
var btn1 = '#<% Button1.ClientID %>';
var btn2 = '#<% Button2.ClientID %>';
$(btn1).click(function(e) {
e.preventDefault();
$(btn2).attr("actIndex", "2");
});
</script>
CodeBehind file
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
Button2.Attributes.Add("actIndex","1");
}
protected void Button2_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
// this should be 2 if button1 has been clicked
string actIndex = btn.Attributes["actIndex"];
}
If I click Button1 then I click Button2 the actIndex value is still "1" but if I use page inspect the Button2 actIndex attribute is "2", somehow the attribute value is not passed to postBack action.
How can I solve this mystery?
I think the problem you have is because the attributes are not being posted back to have their information rebuilt server side.
The control's state is built server side and stored in the ViewState before it serves up the page. Then you modify the value using javascript which has no effect because that vaule is not being posted back to the server. On PostBack, the server rebuilds the control from the known ViewState which has the default value you originally assigned which is the value 1.
To get around this you need to store the value in some type of control (thinking a HiddenField control) that will get posted back to the server and then rebuild the attribute server side.
eg (semi pseudo code):
// In your javascript write to a hidden control
$("#yourHiddenFieldControlName").val("2");
// Then in your server side c# code you look for this value on post back and if found,
// assign it to you attribute
if (!string.IsNullOrEmpty(yourHiddenFieldControlName.Value))
{
Button2.Attributes["actIndex"] = yourHiddenFieldControlName.Value;
}
Your control needs to be handled manually if you are modifying it client side with javascript.
only form elements can actually postback data. The server side will take the postback data and load it into the form element provided that the runat=server is set.
in markup or html:
<input type="hidden" runat="server" ID="txtHiddenDestControl" />
javascript:
document.getElementById('<%= txtHiddenDestControl.ClientID %>').value = '1';
code behind:
string postedVal = txtHiddenDestControl.Value.ToString();
NO need for Javascript below code will work for you
protected void Page_Load(object sender, EventArgs e)
{
Button2.Attributes.Add("actIndex", "1");
}
protected void Button1_Click(object sender, EventArgs e)
{
string Value = Button2.Attributes["actIndex"].ToString();//1
Button2.Attributes.Remove("actIndex");
Button2.Attributes.Add("actIndex", "2");
Value = Button2.Attributes["actIndex"].ToString();//2
}

CheckList Box inside a gridview shows alert only when if it is not postback as the function is called on rowbound of grid

I have CheckListBox inside a GridView. I need an alert when the checkbox gets clicked. It is currently done on the Gridview.RowDataBound() event, so it happens only one time in if it is not postback. How do I make the alert to work every time when the page loads.
You can do it using jquery like below:
<head>
<title></title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", "input:checkbox", function () {
alert(this.checked);
});
});
</script>
</head>
Make sure you're doing something like this in your RowDataBound event.
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var cbListSource = getDataSource(); // get the data source values for the checkboxlist to bind to
CheckBoxList cblItems = (CheckBoxList)e.Row.FindControl("cblItems");
cblItems.DataSource = cbListSource;
cblItems.DataTextField = "QuestionName";
cblItems.DataValueField = "QuestionId";
cblItems.DataBind();
cblItems.Attributes.Add("onclick", "alert('Your alert text goes in here')");
}
}
Alternatively you can use javascript or jquery to achieve the same result.

tab container - event is not firing

i am creating a tab container at runtime and make 1 of the column member as the tab header
once user click on the tab i want to fire the event ActiveTabChanged.. if autopostback=true the entire tab container will gone but it got commend inside the event. if autopostback=false it can't go in the event and nothing happen at the layout.. hence i change the concept of my code..what i want is when user click on tab.. event are fire > everything remain same > next asp.net function will be call from the event. below are my coding
Remark- TabC is the tab container
<script type="text/javascript">
function ActiveTabChanged(sender, e) {
var Current_Tab = $get('<%#TabC.ClientID%>');
Current_Tab.innerHTML = sender.get_activeTab().get_headerText();
__doPostBack('TabC', sender.get_activeTab().get_headerText());
//Highlight(TabC);
}
</script>
in the body
<asp:TabContainer ID="TabC"
runat="server"
OnClientActiveTabChanged="ActiveTabChanged"
OnActiveTabChanged="ActiveTabChangedServer"
ActiveTabIndex="0"
/>
at Page Load
UpdatePanel oUpdatePanel = new UpdatePanel();
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
protected void Page_Load(object sender, EventArgs e)
{
trigger.ControlID = "TabC";
trigger.EventName = "ActiveTabChanged";
oUpdatePanel.Triggers.Add(trigger);
Page.Header.DataBind();
ScriptManager.RegisterAsyncPostBackControl(TabC);
if (!Page.IsPostBack)
{
//runtime generate tab and gridview
Bind_Category_with_Tab();
}
}
error i get
output
the main problem is.. when i fire any event of the component in the page every things will disappear.. if the event can be trigger (AutoPostBack="true")
what mistake i have been done here? please to give a help here.. thanks advance

How can i get ASP.Net Grid Element using Javascript

I am using a Grid View in asp.net, i want to get Element on clicking a grid, how can i do so?
A grid has a column id, name, warp, weft, etc, i want to pick the selected cell data using Javascript, let me know.
Please help...
Regards
Atif
To track which row button is clicked, you have to set the row Index as a parameter to a JS function like...
protected void grdForecast_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType ==DataControlRowType.DataRow )
{
((Button)e.Row.FindControl("buttonId")).Attributes.Add("onclick", "javascript:update(" + (e.Row.RowIndex ) + ");");
}
}
And then in JavaScript:
<script language="javascript" type="text/javascript">
function update(ri) {
var grd = document.getElementById('<%= GridView1.ClientID %>');
SecondCellValue = grd.rows[ri].cells[1].childNodes[0].value
ThirdCellValue = grd.rows[ri].cells[2].childNodes[0].value
}
</script>
Do you have a control inside the cell that you can reference? If not, then you can create a hidden control. Then you can write out the control's client id to the client side in the PreRender event handler via ScriptManager. And you can then get a hold of that element by id and find other content inside that parent cell.
Alternatively, you can use jquery to handle cell click events...
$('#myTable td').click(function () {
alert($(this).html());
});

Categories