ModalPopUp as User Control ASP.NET C# - c#

Im trying build a ModalPopUp as Control. Its have theses controls:
TextBox- placeholder for filter
Button - Search Button
Button - Cancel Button
GridView - To show results
Screen of Search
<ajax:toolkitscriptmanager id="searchPopUp" runat="server"></ajax:toolkitscriptmanager>
<asp:Panel
BackColor="White"
ID="searchPanel"
CssClass="modalPopup"
runat="server"
Style="display: table">
<div class="myContainer">
<uc1:ScreenSearch
runat="server"
ID="mySearch" />
<asp:Button ID="btnToHide" runat="server" Text="Tohide" Style="display: none" />
<asp:Button ID="btnToShow" runat="server" Text="ToShow" Style="display: none" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender
ID="ModalPopUpSearch"
runat="server"
TargetControlID="btnToShow"
PopupControlID="searchPanel"
CancelControlID="btnToHide"
DropShadow="true"
BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
code behind of : uc1:ScreenSearch
protected void Page_Load(object sender, EventArgs e){...}
protected void fillGridView()
{
myDao dao = new myDao();
DataSet ds = new DataSet();
ds = dao.retornarPesquisa(txtFilter.Text); //return data source
DataTable dt = new DataTable();
gv.DataSource = ds;
gv.DataBind();
}
uc1:ScreenSearch is my control that contain a TextBox, Button(perform search calling the method: fillGridView()) and GridView.
When I try perform the search click Binding the GridView. What the best way to get results in this GridView of my User Control?

You haven't posted any of your code so it's hard to tell why it's not working.Below is a working example which displays a Bootstrap modal popup -> allows a user to search -> displays the results in a GridView inside the modal popup:
Code behind:
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
}
public partial class ModalPopupFromGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSearch_Click(object sender, EventArgs e)
{
//Use txtSearch.Text to lookup the data you want to bind to the GridView, mine is hardcoded for the sake of simplicity
var p1 = new Person { Name = "Name 1", Surname = "Surname 1" };
var p2 = new Person { Name = "Name 2", Surname = "Surname 2" };
GridView1.DataSource = new List<Person> { p1, p2 };
GridView1.DataBind();
ScriptManager.RegisterStartupScript(this, this.GetType(), "myModal", "showPopup();", true);
}
}
.ASPX:
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script type="text/javascript">
//It'svery important that showPopup() is outside of jQuery document load event
function showPopup() {
$('#myModal').modal('show');
}
$(function () {
$(".show").click(function () {
showPopup();
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
Show Popup
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Details</h4>
</div>
<div class="modal-body">
<asp:TextBox ID="txtSearch" runat="server">
</asp:TextBox><asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
<br /><br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Surname" HeaderText="Surname" />
<asp:TemplateField HeaderText="User Details">
<ItemTemplate>
<a class="details" href="#" data-name='<%# Eval("Name") %>' data-surname='<%# Eval("Surname") %>'>Details</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</form>
</body>
Output:

Check if the search buttons autopostback is set to true. Also you will get the event of search button click in gridview_itemchanged event as the search button is inside gridview control. Hope that will work

Related

User to role gets created but when refreshing web page the web site crashes

I have a problem which I don;t know how to resolve. Whats happening is that when the user (Admin) assigns a user to a role and saves it closes the page and redirects to the index.aspx page. All of this works great and when assigning another user to a role the previous user/role is displayed in my gridview. However when refreshing the web page I get the following:
The page that you're looking for used information that you entered.
Returning to that page might cause any action you took to be repeated. Do
you want to continue?
And when clicking on continue:
System.Configuration.Provider.ProviderException: 'The user 'qwerty' is
already in role 'Client'.'
This is my code I have: C#
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DisplayRolesInGrid();
BindList();
DisplayUserRolesInGrid();
}
}
private void DisplayUserRolesInGrid()
{
using (CustomMembershipEntities dataContext = new CustomMembershipEntities())
{
dataContext.Connection.Open();
var UserRole = (from u in dataContext.aspnet_Users.Include("aspnet_Roles")
from r in u.aspnet_Roles
where r != null
select new { User = u, Role = r }).ToList();
grdUserRoles.DataSource = UserRole.ToArray();
grdUserRoles.DataBind();
}
}
private void BindList()
{
foreach (var role in Roles.GetAllRoles())
{
ddlRole.Items.Add(new ListItem(role, role));
}
foreach (MembershipUser user in Membership.GetAllUsers())
{
ddlUser.Items.Add(new ListItem(user.UserName, user.UserName));
}
}
protected void btnRoleAssign_Click(object sender, EventArgs e)
{
string roleName = ddlRole.SelectedItem.Text;
string userName = ddlUser.SelectedItem.Text;
if (!User.IsInRole(roleName))
{
Roles.AddUserToRole(userName, roleName);
DisplayUserRolesInGrid();
}
}
}
}
And then in aspx
<div class="modal fade" id="AssignModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="AssignModalLabel">Assign User Role</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="container">
<br />
<p>
Select Role:
<asp:DropDownList ID="ddlRole" runat="server"></asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvRole" runat="server"
ControlToValidate="ddlRole" Display="Dynamic"
ErrorMessage="*"></asp:RequiredFieldValidator>
</p>
<br />
<p>
Select User:
<asp:DropDownList ID="ddlUser" runat="server"></asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvUser" runat="server"
ControlToValidate="ddlUser" Display="Dynamic"
ErrorMessage="*"></asp:RequiredFieldValidator>
</p>
<br /><br />
<asp:GridView ID="grdUserRoles" runat="server" AutoGenerateColumns="False" CssClass="Grid">
<Columns>
<asp:TemplateField HeaderText="User">
<ItemTemplate>
<%# Eval("User.UserName")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role">
<ItemTemplate>
<%# Eval("Role.RoleName")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br /><br />
<div class="modal-title">
<asp:Button ID="btnRoleAssign" runat="server" Text="Assign Role" OnClick="btnRoleAssign_Click" />
</div>
<br />
<br />
</div>
</div>
</div>
</div>
I have no idea on how to resolve this?
Thanks
You get the message from your browser, as refreshing the page after assigning a role would cause re-executing that action (assigning a role) again, which probably is not what you want.
Using a Redirect you should be able to bypass that behavior, as simplified speaking the last action assigning the role is replaced with showing your aspx file.
protected void btnRoleAssign_Click(object sender, EventArgs e)
// ...
Response.Redirect("YourAspxFile.aspx");
}

Create html elements from code behind and display to front-end in ASP.NET Web Form

I need to Read/Display some front-end code/elements from Code Behind.
Scenario: I have a page, in which I have two (2) <div>, the top <div> and the bottom <div>.
I have two buttons inside top <div> as given below and the <div> at bottom is blank. Below is the code snippet:
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="navbar">
<asp:Button ID="btnHome" runat="server" Text="Home"
OnClick="btnHome_Click" />
<asp:Button ID="btnProducts" runat="server" Text="Products"
OnClick="btnProducts_Click" />
</div>
<div id="contentArea">
</div>
</form>
</body>
</html>
When I click the home button, some HTML elements should become part of the Default.aspx page inside a <div> given below:
<div id=contentArea">
</div>
The above code should look like the code below:
<div id="contentArea">
<h1>Home</h1>
<p>Home Elements here</p>
</div>
When I click Product button, so that the code look like:
<div id="contentArea">
<h1>Products</h1>
<p>Products Elements here</p>
<asp:HyperLink ID="lnkMicrosoft" runat="server" Text="Go to Microsoft"
NavigateUrl="http://www.microsoft.com"></asp:HyperLink>
<asp:HyperLink ID="lnkGoogle" runat="server" Text="Go to Google"
NavigateUrl="http://www.google.com"></asp:HyperLink>
</div>
You can use Panel to display html contents which renders as div tag.
For example,
ASPX
<div id="navbar">
<asp:Button ID="btnHome" runat="server" Text="Home" OnClick="btnHome_Click" />
<asp:Button ID="btnProducts" runat="server" Text="Products"
OnClick="btnProducts_Click" />
</div>
<asp:Panel ID="contentArea" runat="server">
</asp:Panel>
Code Behind
protected void btnHome_Click(object sender, EventArgs e)
{
var h1 = new HtmlGenericControl("h1") {InnerText = "Home"};
contentArea.Controls.Add(h1);
var p = new HtmlGenericControl("p") {InnerText = "Home Elements here"};
contentArea.Controls.Add(p);
}
protected void btnProducts_Click(object sender, EventArgs e)
{
var h1 = new HtmlGenericControl("h1") {InnerText = "Products"};
contentArea.Controls.Add(h1);
var p = new HtmlGenericControl("p") {InnerText = "Products Elements here"};
contentArea.Controls.Add(p);
var lnkMicrosoft = new HyperLink
{
Text = "Go to Microsoft",
NavigateUrl = "http://www.microsoft.com"
};
contentArea.Controls.Add(lnkMicrosoft);
var lnkGoogle = new HyperLink
{
Text = "Go to Google",
NavigateUrl = "http://www.google.com"
};
contentArea.Controls.Add(lnkGoogle);
}

ASP.NET How to bind data in DropDownList outside GridView?

I am creating a web aplication to access data in a SQL Server 2008 database. I show the data in a Gridview and I can succesfully edit the rows (even with DropDownLists), but I want to implement the edit of those records with a modal dialog/popup using Bootstrap.
However, I can not get working these DropDownLists in this modal, because resides in a DIV outside the <asp:GridView> element. I can bind others text fields in the modal dialog, with this code (the modal dialog is fired with a command ) [code_behind]:
if (e.CommandName.Equals("editRecord"))
{
GridViewRow gvrow = GridView2.Rows[index];
txtRUT.Text = HttpUtility.HtmlDecode(gvrow.Cells[2].Text);//.ToString();
txtDIGITO.Text = HttpUtility.HtmlDecode(gvrow.Cells[3].Text);
txtCOD_FISA.Text = HttpUtility.HtmlDecode(gvrow.Cells[4].Text);
txtNOMBRE.Text = HttpUtility.HtmlDecode(gvrow.Cells[5].Text);
//ddlCARGO is the DropDownList
ddlCARGO.Text = HttpUtility.HtmlDecode(gvrow.Cells[6].Text);
lblResult.Visible = false;
//I know that the DropDownList ist outside the GridView, but i don't know how to access/bind data to it
DropDownList combo_cargo = GridView2.Rows[index].FindControl("ddlCARGO") as DropDownList;
if (combo_cargo != null)
{
combo_cargo.DataSource = DataAccess.GetAllCargos(); //in GridView default edit mode, this works OK
combo_cargo.DataTextField = "cargo";
combo_cargo.DataValueField = "idCARGO";
combo_cargo.DataBind();
}
combo_cargo.SelectedValue = Convert.ToString(HttpUtility.HtmlDecode(gvrow.Cells[6].Text));
}
The modal html code [.aspx]:
<!-- EDIT Modal Starts here -->
<div id="editModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close"
data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="editModalLabel">Editar Empleado</h3>
</div>
<asp:UpdatePanel ID="upEdit" runat="server">
<ContentTemplate>
<div class="modal-body">
<p> Nombre: <asp:TextBox ID="txtNOMBRE" runat="server" columns="40"></asp:TextBox> </p>
<p>RUT: <asp:TextBox ID="txtRUT" runat="server" columns="8"></asp:TextBox> -
<asp:TextBox ID="txtDIGITO" runat="server" columns="1"></asp:TextBox></p>
<p>Código Fisa: <asp:TextBox ID="txtCOD_FISA" runat="server" columns="7"></asp:TextBox></p>
<%--<p>Cargo: <asp:TextBox ID="txtCARGO" runat="server" columns="7"></asp:TextBox></p>--%>
<p>Cargo: <asp:DropDownList ID="ddlCARGO" runat="server"></asp:DropDownList></p>
<%-- <p>Estado: <asp:TemplateField HeaderText="ESTADO" SortExpression="idESTADO">
<EditItemTemplate>
<asp:DropDownList ID="ddlESTADO" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblESTADO" runat="server" Text='<%# Bind("ESTADO") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField> </p> --%>
</div>
<div class="modal-footer">
<asp:Label ID="lblResult" Visible="false" runat="server"></asp:Label>
<asp:Button ID="btnSave" runat="server" Text="Update" CssClass="btn btn-info" OnClick="btnSave_Click" />
<button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView2" EventName="RowCommand" />
<asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</div>
<!-- Edit Modal Ends here -->
I can give you an idea.
Create a DIV/user control with those controls that you need to edit.
On ROW click - open the DIV in model (jq you can use) and then either pass the Row content to the Model.open Or pass some unique ID of that ROW and load again from DB the Row corresponding detail. And allow editing there and on Save over there - saving to DB with that unique ID preserved.
Let us know
Finally I have found the solution:
Modal html (.aspx):
<div class="form-group">
<asp:TextBox ID="txtCARGO" runat="server" CssClass="hiddencol"></asp:TextBox> <%--data value field (hidden with CSS)--%>
<label class="col-xs-3 control-label" for="editModalCargo">Cargo</label>
<div class="col-xs-3 input_medio">
<asp:DropDownList id="editModalCargo" runat="server" name="editModalCargo" class="form-control input-md"/> <%--data text field--%>
</div>
</div>
<div class="form-group hiddencol"> <%--field with row id (hidden with CSS)--%>
<asp:TextBox ID="txtID" runat="server" columns="2"></asp:TextBox>
</div>
I've put OnRowCommand="GridView2_RowCommand" on <asp:GridView> and created a <asp:ButtonField> with CommandName="editRecord"> to edit the row.
Code behind (.aspx.cs):
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName.Equals("editRecord"))
{
GridViewRow gvrow = GridView2.Rows[index];
txtID.Text = HttpUtility.HtmlDecode(gvrow.Cells[17].Text); //Pass value from Gridview's column to <asp:TextBox ID="txtID">
txtCARGO.Text = HttpUtility.HtmlDecode(gvrow.Cells[13].Text); //Pass value from Gridview's column to <asp:TextBox ID="txtCARGO">
lblResult.Visible = false;
BindEditCargo(txtCARGO.Text);
}
}
private void BindEditCargo(string cargoValue) //Populates <asp:DropDownList id="editModalCargo">
{
editModalCargo.DataSource = DataAccess.GetAllCargos();
editModalCargo.DataTextField = "cargo";
editModalCargo.DataValueField = "idCARGO";
// Bind the data to the control.
editModalCargo.DataBind();
// Set the default selected item, if desired.
editModalCargo.SelectedValue = cargoValue;
}
DataAccess.cs:
public static DataTable GetAllCargos()
{
DataTable dt = new DataTable();
string sql = #"SELECT * FROM CARGO";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BRconn"].ToString()))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
return dt;
}
To read the value from modal (to pass it to a Update query for example), you can use (in code behind):
protected void btnSave_Click(object sender, EventArgs e) // Handles Update Button Click Event
{
int idEMPLEADO = Convert.ToInt32(txtID.Text); //Read value from <asp:TextBox ID="txtID">
int idCARGO = Convert.ToInt32(editModalCargo.SelectedValue); //Read value from <asp:DropDownList id="editModalCargo">
DataAccess.UpdateEmpleado(idEMPLEADO, idCARGO); //Update Query
BindData(); //Refresh Gridview
}

Textchange event not working

I am doing a preview of what I am currently typing in a web page using ASP.NET. What I am trying to achieve is that whenever I type or change text in the textbox, the <h3> or label element will also change and always copy what the textbox value is without refreshing the browser. Unfortunately I cannot make it work. Here is what I tried.
.ASPX
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
}
I Tried Adding Autopostback = true... but it only works and refreshes the page and i need to press tab or enter or leave the textbox :(
UPDATE: I Tried This - enter link description here But Still Doesnt Work :(
Just add this script function in your code and in body write onload and call that function.
Javascript:
<script type="text/javascript">
function startProgram() {
setTimeout('errorcheck()', 2000);
}
function errorcheck() {
setTimeout('errorcheck()', 2000);
document.getElementById("NewsTitlePreview").innerText = document.getElementById("Titletxt").value
document.getElementById("NewsContentPreview").innerText = document.getElementById("Contenttxt").value
}
</script>
<body onload="startProgram();">
<form id="form1" runat="server">
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" ></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</form>
</body>
You are right in your analysis of the behavior of the control (it only fires the event when you leave the control), even when you have AutoPostBack="True".
MSDN says it all:
The TextBox Web server control does not raise an event each time the user enters a keystroke, only when the user leaves the control. You can have the TextBox control raise client-side events that you handle in client script, which can be useful for responding to individual keystrokes.
So you either have to be satisfied with the current behavior, or set up some client side event handling to do some validation, etc. client side.
Download and include JQuery library. And also modify title and content textbox so they don't change their Id's
Title
<asp:TextBox ID="Titletxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Then add this script and it will work.
<script>
$(document).ready(function () {
$('#Titletxt').on('input', function () {
$("#NewsTitlePreview").text($(this).val());
});
$("#Contenttxt").on('input',function () {
$("#NewsContentPreview").text($(this).val());
});
});
</script>
One of the best idea...
Just change your code to this. it works
ASPX
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ViewStateMode="Enabled">
<ContentTemplate>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
UpdatePanel1.Update();
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
UpdatePanel1.Update();
}
Try this it will work this how change event call using jquery dont forget to add google apis
<script>
$('#txtbox').change(function() {
alert("change Event");
});
</script>

How do I update UpdatePanel on OnUploadedComplete event of AsyncFileUploader?

I need to upload an avatar to server in 3 steps using Ajax:
Choose file to upload.
Choose crop zone using jquery.Jcrop.js.
Create avatar and save it to DB.
I have created a user control to implement it. So user clicks the upload button and there is a modalPopUpExtender shows dialog box where users have to choose the file to upload (using AjaxToolKit File async uploader), after the file is uploaded the second PopUp extender has to show the uploaded image in another dialog box to let the user choose the rectangle to crop. And the last step (button click "Create") is to crop image and show it in the parent page. I'm successful with first step. But I can't make the uploaded image to be displayed in the second dialog box.
So here is my complete ascx file and its code behind:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Avatar.ascx.cs" Inherits="KR.Trivital.Web.UI.Controls.Avatar" %>
<script type="text/javascript">
window.onload = function () { $addHandler($get('ctl00_CntAvatarBox_ImgButtAvatarImage'), 'click', showOverlay); }
function showOverlay() {
var bid = $find('mpeBehaviorID');
bid.show();
}
function uploadComplete(sender, args) {
var bid = $find('mpeBehaviorID');
bid.hide();
var bid2 = $find('ModalPopupExtender1BehaviorID');
bid2.show();
}
</script>
<asp:UpdatePanel runat="server" ID="UpdPan">
<ContentTemplate>
<asp:Image runat="server" ID="ImgAvatarImage" Visible="false" />
<asp:ImageButton runat="server" ID="ImgButtAvatarImage" Visible="false" OnClientClick="return false;" />
<asp:Panel ID="panPopupUpload" runat="server" CssClass="popUpDetails" Width="550" Style="display: none">
<h2 class="popPanelH2"><asp:Literal runat="server" ID="ltrUploadHeader" Text="Загрузка аватара" /></h2>
<div style="background-color: Gray; padding: 20px;">
<asp:Button ID="btnShowPopupUpload" runat="server" Style="display: none" />
<asp:Button ID="btnCancelPopupUpload" runat="server" Style="display: none" />
<ajaxToolkit:ModalPopupExtender ID="mdlPopupUpload" runat="server" TargetControlID="btnShowPopupUpload"
PopupControlID="panPopupUpload" CancelControlID="btnCancelPopupUpload" BackgroundCssClass="modalBackground"
BehaviorID="mpeBehaviorID" />
<ajaxToolkit:AsyncFileUpload runat="server" ID="AsncUpload1" OnUploadedComplete="AsncUpload1_UploadedComplete"
OnClientUploadComplete="uploadComplete" />
</div>
</asp:Panel>
<asp:Panel ID="panPopupCropper" runat="server" CssClass="popUpDetails" Width="550" Style="display: none">
<h2 class="popPanelH2"><asp:Literal runat="server" ID="Literal1" Text="Выбор обрезного формата" /></h2>
<div style="background-color: Gray; padding: 20px;">
<asp:Button ID="Button1" runat="server" Style="display: none" />
<asp:Button ID="Button2" runat="server" Style="display: none" />
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="Button1"
PopupControlID="panPopupCropper" CancelControlID="Button2" BackgroundCssClass="modalBackground"
BehaviorID="ModalPopupExtender1BehaviorID" />
<img runat="server" id="Img1" alt="" />
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
codebehind:
using System;
using KR.Trivital.Web.Core;
using KR.Trivital.Business.Users;
using System.Web;
using System.Drawing.Drawing2D;
using System.IO;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.UI;
namespace KR.Trivital.Web.UI.Controls
{
public partial class Avatar : SharedBaseControl
{
protected void Page_Load(object sender, EventArgs e)
{
this.Visible = Page.User.Identity.IsAuthenticated;
var avatar = UserAvatarBO.Get(CurrentUserId);
if (avatar != null)
{
ImgAvatarImage.ImageUrl = avatar.ImagePath;
ImgAvatarImage.Visible = true;
}
else
{
ImgButtAvatarImage.Visible = true;
}
}
protected void lnkButtUpload_Click(object sender, EventArgs e)
{
// Показать панель загрузки
mdlPopupUpload.Show();
}
private AvatarUploader InitializeAvatarUploader()
{
var uploader = new AvatarUploader();
uploader.SmoothingMode = SmoothingMode.HighQuality;
uploader.OffSetMode = PixelOffsetMode.HighQuality;
uploader.ResizingInterpolationMode = InterpolationMode.HighQualityBicubic;
uploader.ThumbMaxHeight = SiteConfig.UserAvatarsSettings.AvatarHeight;
uploader.ThumbMaxWidth = SiteConfig.UserAvatarsSettings.AvatarWidth;
uploader.IntermidiaMaxHeight = SiteConfig.UserAvatarsSettings.UploadHeight;
uploader.IntermidiaMaxWidth = SiteConfig.UserAvatarsSettings.UploadWidth;
uploader.JpgQuality = SiteConfig.UserAvatarsSettings.AvatarQuality;
uploader.UploadFolder = SiteConfig.UserAvatarsSettings.UploadFolder + "/" + this.Page.User.Identity.Name;
return uploader;
}
protected void AsncUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
var uploader = InitializeAvatarUploader();
string returnPath = "";
uploader.UploadImage(AsncUpload1.FileContent, AsncUpload1.FileName, ref returnPath);
Img1.Src = "~/" + returnPath;
}
}
}
This is a "creative solution", but it does work.
It uses the AsyncFileUpload's OnClientUploadComplete you're already using and a Control on your page that will trigger an update on your UpdatePanel (e.g. a Button; can have display:false if you like).
function uploadComplete(sender, args) {
// Your code
__doPostBack('<%= UpdatePanelUpdatingControl.UniqueID %>', '');
}

Categories

Resources