I have 2 files in my web site project, Translator2.aspx and Translator2.aspx.cs. I want to add new class (Erwin:Translator2) to my Translator2.aspx.cs file. However it was error like this :
Severity Code Description Project File Line Suppression State
Error 'translator2_aspx' does not contain a definition for 'Switch'
and no extension method 'Switch' accepting a first argument of type
'translator2_aspx' could be found (are you missing a using directive
or an assembly reference?)
C:\Users\erwin.surya\Documents\Visual
Studio 2017\WebSites\WebSite1\Translator2.aspx 33
Here is my Translator2.aspx code:
<%# Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="Translator2.aspx.cs" MasterPageFile="~/Site.Master" Inherits="Translator2" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="English" CssClass="col-md-2 control-label">English</asp:Label>
<div class="col-md-10">
<asp:TextBox Height="79px" TextMode="MultiLine" Width="452px" runat="server" ID="English" CssClass="form-control" />
</div> </div>
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" OnClick="Submit" Height="39px" Width="100px" Text="Translate" CssClass="btn btn-default" />
</div>
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" OnClick="Switch" Height="39px" Width="100px" Text="Switch" CssClass="btn btn-default" />
</div>
<br /><br /><br />
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="Japanese" CssClass="col-md-2 control-label">Japanese</asp:Label>
<div class="col-md-10">
<asp:TextBox Height="79px" TextMode="MultiLine" Width="452px" runat="server" ID="Japanese" CssClass="form-control" />
</div></div>
<br /><br />
<asp:PlaceHolder runat="server" ID="ErrorMessage" Visible="false">
<p class="text-danger">
<asp:Literal runat="server" ID="FailureText" />
</p>
</asp:PlaceHolder>
</asp:Content>
Here is my Translator2.aspx.cs code:
partial class Translator2 : Page
{
public async void Submit(object sender, EventArgs e)
{
string key = "92fcf1387f844a8";
var authTokenSource = new AzureAuthToken(key.Trim());
string authToken;
try
{
authToken = await authTokenSource.GetAccessTokenAsync();
}
catch (HttpRequestException)
{
if (authTokenSource.RequestStatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("Request to token service is not authorized (401). Check that the Azure subscription key is valid.");
return;
}
if (authTokenSource.RequestStatusCode == HttpStatusCode.Forbidden)
{
Console.WriteLine("Request to token service is not authorized (403). For accounts in the free-tier, check that the account quota is not exceeded.");
return;
}
throw;
}
string output = "";
string text = English.Text;
string uri = "https://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + HttpUtility.UrlEncode(text) + "&from=" + "en" + "&to=" + "ja";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Headers.Add("Authorization", authToken);
using (WebResponse response = httpWebRequest.GetResponse())
using (Stream stream = response.GetResponseStream())
{
DataContractSerializer dcs = new DataContractSerializer(Type.GetType("System.String"));
string translation = (string)dcs.ReadObject(stream);
Console.WriteLine("Translation for source text '{0}' from {1} to {2} is", text, "en", "ja");
Console.WriteLine(translation);
output = translation;
}
Japanese.Text = output;
}
class Erwin : Translator2
{
string from, to;
public void SwapStrings(string s1, string s2)
{
string temp = s1;
s1 = s2;
s2 = temp;
from = s1;
to = s2;
testing.Text = from;
testing1.Text = to;
}
protected void Switch(object sender, EventArgs e)
{
string str1 = testing.Text;
string str2 = testing1.Text;
System.Console.WriteLine("Inside Main, before swapping: {0} {1}", str1, str2);
SwapStrings(str1, str2);
}
}
Do you have any idea why I can't add Erwin:Translato2 class? everything works fine before I add the class. Did I miss something?
The Switch method is in a different class than the class that is powering your aspx page. If you want switch to be some kind of utility method, you should create a new class, maybe Erwin in a completely separate file (Erwin.cs), and have a switch method inside that that is public and probably static. I also note that switch doesn't return anything, so not sure what you are trying to accomplish with it.
The OnClick handler for your button should be in the code behind -- ie in the Translator2 class. Inside this handler, you could call Erwin.Switch().
Related
This is my markup:
<%# Page Title="" Language="C#" MasterPageFile="~/User/Default.Master" AutoEventWireup="true" CodeBehind="Consulation.aspx.cs" Inherits="PetShop.User.Consulation" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script>
window.onload = function () {
var second = 5;
setTimeout(function () {
document.getElementById("<%=lblMsg.ClientID%>").style.display = "none";
}, second * 1000)
}
</script>
<link href="../CSSandJS/StyleCss/consulation.css" rel="stylesheet" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<!-- Slider -->
<section id="Slider">
<div class="aspect-ratio-169">
<img src="../CSSandJS/images/bg_1.jpg" alt="">
<img src="../CSSandJS/images/bg_2.jpg" alt="">
<img src="../CSSandJS/images/bg_3.jpg" alt="">
<img src="../CSSandJS/images/bg_4.jpg" alt="">
</div>
<div class="dot-container">
<div class="dot active"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</section>
<!-- End Slider -->
<!-- Free Consulation -->
<section class="contact">
<div class="container-contact">
<h1>Đặt lịch hẹn</h1>
<div class="row">
<div class="contact-img">
<img src="../CSSandJS/images/bg_1.jpg" alt="" width="400">
</div>
<div class="input-infor">
<div class="form">
<div class="dbl-field">
<asp:DropDownList ID="ddlCategory" runat="server" CssClass="form-control option field-mail listOp" DataSourceID="SqlDataSource1" DataTextField="TENDV" DataValueField="MADV" AppendDataBoundItems="true">
<asp:ListItem Value="0">Chọn danh mục</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:cs %>" SelectCommand="SELECT [MADV], [TENDV] FROM [DICHVU]"></asp:SqlDataSource>
</div>
<div class="dbl-field">
<div class="field-mail">
<asp:TextBox ID="txtEmail" runat="server" CssClass="form-control input" placeholder="Nhập email" required></asp:TextBox>
<i class="ri-mail-line"></i>
</div>
</div>
<div class="dbl-field">
<div class="field">
<asp:TextBox ID="txtNameAcc" runat="server" CssClass="form-control input" placeholder="Nhập tên"></asp:TextBox>
<i class="ri-user-line"></i>
</div>
<div class="field">
<asp:TextBox ID="txtSDT" runat="server" CssClass="form-control input" placeholder="Nhập số điện thoại" MaxLength="11"></asp:TextBox>
<i class="ri-phone-line"></i>
</div>
</div>
<div class="dbl-field">
<div class="field">
<asp:TextBox ID="txtNgay" runat="server" CssClass="form-control input" TextMode="Date"></asp:TextBox>
<i class="ri-calendar-2-line"></i>
</div>
<div class="field">
<asp:TextBox ID="txtTime" runat="server" CssClass="form-control input" placeholder="Nhập giờ hẹn" MaxLength="5" TextMode="SingleLine"></asp:TextBox>
<i class="ri-time-line"></i>
</div>
</div>
<div class="message">
<asp:TextBox ID="txtDescription" runat="server" CssClass="form-control textarea" placeholder="Tin nhắn" TextMode="MultiLine"></asp:TextBox>
<i class="ri-message-2-line"></i>
</div>
<div class="button-area">
<asp:Button ID="Add" runat="server" Text="Gửi lịch hẹn" class="btn btn-primary button" OnClick="Add_Click"/>
<asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
<%--<asp:linkbutton id="submitcal" runat="server" cssclass="btn btn-primary button" OnClick="Add_Click">gửi lịch hẹn</asp:linkbutton>--%>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- End Free Consulation -->
</asp:Content>
The textbox doesn't get any value when I debug the program.
I have tested the stored procedure in SQL Server and it works fine. But the data returned from the SQL code is empty.
My button submit code:
namespace PetShop.User
{
public partial class Consulation : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
}
private void clear()
{
txtEmail.Text = string.Empty;
txtDescription.Text = string.Empty;
txtNameAcc.Text = string.Empty;
txtSDT.Text = string.Empty;
txtNgay.Text = string.Empty;
txtTime.Text = string.Empty;
ddlCategory.ClearSelection();
}
protected void Add_Click(object sender, EventArgs e)
{
string actionName = string.Empty;
bool isValidToExcute = true;
con = new SqlConnection(Connection.GetConnectionString());
cmd = new SqlCommand("Add_KHaddLH", con);
cmd.Parameters.AddWithValue("#Action", "INSERT4KH");
cmd.Parameters.AddWithValue("#MaDv", ddlCategory.SelectedValue);
cmd.Parameters.AddWithValue("#EMail", txtEmail.Text.Trim());
cmd.Parameters.AddWithValue("#Ten", txtNameAcc.Text.Trim());
cmd.Parameters.AddWithValue("#Sdt", txtSDT.Text.Trim());
cmd.Parameters.AddWithValue("#NgayHen", txtNgay.Text.ToString());
cmd.Parameters.AddWithValue("#GioHen", txtTime.Text.Trim());
cmd.Parameters.AddWithValue("#GhiC", txtDescription.Text.Trim());
if (isValidToExcute)
{
cmd.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
cmd.ExecuteNonQuery();
actionName = "gửi";
lblMsg.Visible = true;
lblMsg.Text = "Lịch hẹn " + actionName + " thành công!";
lblMsg.CssClass = "alert alert-success";
clear();
}
catch (Exception ex)
{
lblMsg.Visible = true;
lblMsg.Text = "Lỗi !!!" + ex.Message;
lblMsg.CssClass = "alert alert-danger";
}
finally
{
con.Close();
}
}
}
}
}
I think the error lies in the page reload, because when submitting it will delete all the data in the textbox and then enter.
I've tried adding some commands to the button but still can't handle that it keeps losing textbox data.
I update code behind and markup.
Support me,
Thank.
Ok, so that helps a boatload.
if we have this code:
protected void Add_Click(object sender, EventArgs e)
{
string actionName = string.Empty;
bool isValidToExcute = true;
Debug.Print(txtEmail.Text);
output:
So, you might want to put a break point in, or simple add some debug.prints, and see which text box controls are "empty". But, just looking at what you have, those text boxes should be ok.
And including page-load, shows that you not say running the "clear" routine you have. (so, having included the page load event eliminates about 100 possible issues here. This is VERY much why posting some of your code allows the public here to eliminate a 100 "back and forth" suggestions.) So, for example, had you included "clear" routine in page load, then of course page load fires each and every time BEFORE a button click event, so code in page load is VERY OFTEN suspect here. But, since you don't have code in page load event, we scratch that off the table.
So, far, the controls look to have values, but I suggest you add a break point, or some debug.prints as per above to be 100% sure that the controls in fact do not have values.
Also, just pasting in some of the markup, we see things like this:
So, you do have stray "garbage" in a number of places. (not good).
As it stands, with the posted markup, I MOST certainly do get/see/have/enjoy/observe that the text boxes are intact, do have values.
Given we can't re-produce your issue?
I suggest creating a blank new page, drop in some of those controls, and try a test button - (don't even bother with the database save code - we NOT gone that far down the debugging road just yet).
So, only thing so far?
Are you 100% sure the text boxes don't have values, and you tested this BEFORE any of the database save code runs?
and do remove the stray "required" markup in that txtEmail box, the editor even HONKS OUT AT YOU that the markup is bad as per above screen shot.
In fact, drop in another button on the form, and its only job would be to debug print out the text boxes - does that work?
As it stands now, you don't have a re-producable error, and the community in general here has not, does not see your error, nor are we the viewing public EVEN able to re-produce that these text boxes don't have values.
As a result, there information we don't have to re-produce the error.
I suggest building a page with just the txtEmail that is blank, and a simple button. if that works, then start adding markup from that other page until it stops working, since we here can't re-produce your issue with the provided code and markup you have provided.
And, since you using a master page, then check if page load in master page has any code that runs on page load.
I'm working on a asp.net project. I've been asked to create a page so site admins could add articles and everyone else could add comments under those articles.
I have 2 separate tables in my db, Articles/Comments. On page load I'm populating all the articles with their own related comments within a panel.
I've also been asked to use an accordion so all comments would display in a collapsible manner!
My problem is that only the first article shows up with collapsible comments under it, and the rest do not!
Here is my aspx page:
<%# Page Title="Ref Notes" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="RefNotes.aspx.cs" Inherits="Root.RefNotes" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:Panel ID="refNotes" CssClass="col-xs-12 data-container" runat="server">
</asp:Panel>
</asp:Content>
aspx.cs code:
public partial class RefNotes : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
populateNotes();
Page.Title = "Latest Ref Notes";
}
protected void populateNotes()
{
string tag = "";
if (Request.QueryString["tag"] != null) tag = Request.QueryString["tag"];
int post = 0;
if (Request.QueryString["post"] != null) post = Int32.Parse(Request.QueryString["post"]);
MediaService.Article[] articles = Global.mediaService.GetArticles(1, 1); //gets all articles
for (int i = 0; i < articles.Length; i++)
{
if (post > 0 && articles[i].ID != post) continue;
Root.Controls.Blog.RefNotesPost p = (Root.Controls.Blog.RefNotesPost)LoadControl("~/Controls/Blog/RefNotesPost.ascx");
p.SetData(articles[i]);
refNotes.Controls.Add(p);
Root.Controls.Blog.CommentControl c = (Root.Controls.Blog.CommentControl)LoadControl("~/Controls/Blog/CommentControl.ascx");
c.SetData(articles[i].ID);
refNotes.Controls.Add(c);
}
if (articles.Length == 0)
{
Literal l = new Literal();
l.Text = "<h1>No content currently available.</h1>";
refNotes.Controls.Add(l);
}
}
}
CommentControl.ascx code:
# Control Language="C#" AutoEventWireup="true" CodeBehind="CommentControl.ascx.cs" Inherits="Root.Controls.Blog.CommentControl" %>
<div class="row">
Comments:
<asp:Panel ID="errorPanelID" runat="server" CssClass="loginbox-textbox" Visible="false" Style="margin-top: 20px;">
<div class="alert alert-danger fade in">
<button class="close" data-dismiss="alert">
×
</button>
<i class="fa-fw fa fa-times"></i>
<asp:Label ID="errorMsgID" runat="server"></asp:Label>
</div>
</asp:Panel>
</div>
<div id="dvAccordion" style="width: auto">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<h3>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("user") + " at " + Eval("dateTime") + " says:"%>'></asp:Label></h3>
<div style="background-color: #CFDEE3">
<asp:Literal ID="lit" runat="server" Text='<%#Eval("comment")%>' Mode="Transform" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div>
Add a Comment:<br />
<asp:TextBox ID="txtComment" runat="server" Rows="5" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" OnClick="saveBtn_Click" Text="Submit " />
<asp:HiddenField runat="server" ID="articleID" Value="0" />
</div>
<script type="text/javascript">
$(function () {
$("#dvAccordion").accordion();
});
</script>
CommentControl.ascx.cs code:
public partial class CommentControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void SetData(int artID)
{
Services.Comment[] comments = Global.Tools.GetComments(artID);
articleID.Value = artID.ToString();
if (comments.Length > 0)
{
Repeater1.Visible = true;
Repeater1.DataSource = comments;
Repeater1.DataBind();
}
else
{
Repeater1.Visible = false;
}
}
protected void saveBtn_Click(object src, EventArgs e)
{
AdminService.Employee emp = Global.Tools.GetEmployee(Int32.Parse(Session["eid"].ToString()));
Blog.Comment a = new Blog.Comment();
a.CommentOn = txtComment.Text;
a.CreatedBy = emp.username;
a.DatePosted = DateTime.Now;
a.isVisible = 1;
a.ArticleID = int.Parse(articleID.Value);
if (Request.QueryString["post"] != null)
{
a.ID = Int32.Parse(Request.QueryString["post"]);
}
int result = Global.Tools.CreateComment(a);
if (result <= 0)
{
errorMsgID.Text = "Failed to create comment.";
errorPanelID.Visible = true;
}
else
{
Response.Redirect("/News.aspx");
}
}
txtComment.Text = string.Empty;
}
In the CommentControl.ascx file I had set the accordion based on id (#dvAccordion). I changed it to be based on class (.dvAccordion) and that solved the issue.
So for future references: when you're on a page an "id" can only be called once but a "class" can be called multiple times!
**ASPX CODE** this is the aspx code
<% for (int i = 0; i < pricePageObj.cartItemsgetset; i++)
{ %>
<div class="row">
<div class="col-md-1 ">
<% Response.Write(i + 1); %>
</div>
<div class="col-md-2 ">
<% Response.Write(svcID[i]); %>
</div>
<div class="col-md-2 ">
<% Response.Write(svcName[i]); %>
</div>
<div class="col-md-3 ">
<% Response.Write(svcDesc[i]); %>
</div>
<div class="col-md-2 ">
<% Response.Write(svcCharges[i]); %>
</div>
<div class="col-md-1 ">
<asp:Button CssClass="btn btn-danger" runat="server" Text="Remove" CommandArgument="dont know how to pass i here" OnCommand="onRemove" />
</div>
</div>
<%} %>
Let's say i=0 ; i<5; i++. so for loop will go for 5 times. so i want to send i as a parameter in the code behind to read the value of i.
C# CODE code behind
public void onRemove(object sender, CommandEventArgs e)
{
try
{
string indexx = Convert.ToString(e.CommandArgument);
System.Diagnostics.Debug.WriteLine("String index = " + indexx);
}
catch (Exception ex)
{
}
}
I want to send that 'i' index in the code behind. Any help?
When i clicked on the button, i want to read that i in the onRemove event.
any help?
Here is how we normally display a collection inside Bootstrap divs in ASP.NET Web Form. If we want to manipulate individual row, we use ItemDataBound event.
It seems a lot of code compare to your original question, but this is a recommended approach in ASP.NET Web Form.
<asp:ListView runat="server" ID="ListView1"
ItemPlaceholderID="ItemPlaceholder"
OnItemDataBound="ListView_ItemDataBound">
<LayoutTemplate>
<asp:Panel runat="server" ID="ItemPlaceholder"></asp:Panel>
<asp:DataPager runat="server" ID="DataPager" PageSize="3">
<Fields>
<asp:NumericPagerField ButtonCount="5" PreviousPageText="<" NextPageText=">" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<div class="row">
<div class="col-md-1">
<%# Eval("Id") %>
</div>
<div class="col-md-2">
<%# Eval("Name") %>
</div>
<div class="col-md-1">
<asp:Button CssClass="btn btn-danger" runat="server" Text="Remove"
CommandArgument='<%# Eval("Id") %>' ID="RemoveButton"
OnCommand="RemoveButton_Command" />
</div>
</div>
</ItemTemplate>
</asp:ListView>
Code Behind
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListView1.DataSource = new List<User>
{
new User {Id = 1, Name = "John"},
new User {Id = 2, Name = "Marry"},
new User {Id = 3, Name = "Nancy"},
new User {Id = 4, Name = "Eric"},
};
ListView1.DataBind();
}
}
protected void RemoveButton_Command(object sender, CommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument);
}
protected void ListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
User user = e.Item.DataItem as User;
}
}
}
<% Response.Write(i + 1); %>
By doing this, you are passing i to the Response.Write method.
You should be able to just write a method in your code behind.
Code behind sample method:
protected int Foo(int bar){
//do something with bar
return bar;
}
You should be able to do this on the .aspx page now:
<% Response.Write(Foo(1) + 1); %>
You can access all of the methods in your code behind by putting the below line at the top of your page, replacing MyCoolPage with your page name. This line should be added for you automagically, though, when you create a web form page:
<%# Page CodeBehind="MyCoolPage.aspx.cs" Inherits="MyCoolPage" Language="C#" %>
Instead of doing what you are doing with your button, just add an OnClick event instead of what you are doing now, as follows:
<asp:Button CssClass="btn btn-danger" runat="server" Text="Remove" OnClick="DoSomethingCool(i) />
DoSomethingCool:
protected void DoSomethingCool(int index){
try
{
System.Diagnostics.Debug.WriteLine("index = " +
index);
}
catch (Exception ex)
{
}
}
I am using Ajax with asp.net C#. What I am trying to do is, on click of a link, a div should appear. A div contains file upload controls and a button named 'Upload Files'. When upload files button is clicked, it is checking if any of the file upload controls has files. If yes, it uploads files to some directory and updates a label to show how many files are uploaded 0 or more. Here is the screenshot to explain:
Here's the code snippet, I am using Ajax with asp.net C#
<div class="form-group row">
<asp:UpdatePanel runat="server" id="UpdatePanel1" updatemode="Conditional">
<ContentTemplate>
<div class="col-xs-5">
<% if (Session["MemberID"]!= null)
{%>
<asp:LinkButton ID="insertMore" runat="server" OnClick="insertMoreclicked">(Insert More Attachments)</asp:LinkButton>
<%} %>
</div><br />
<div id="moreUploadsDiv" runat="server" visible="false">
<br />
<asp:FileUpload ID="moreUpload1" runat="server" />
<asp:FileUpload ID="moreUpload2" runat="server" />
<asp:FileUpload ID="moreUpload3" runat="server" />
<asp:FileUpload ID="moreUpload4" runat="server" />
<asp:Button ID="uploadMoreFilesBtn" runat="server" Text="Upload" OnClick ="uploadMoreClicked" CausesValidation="false" />
<br />
<asp:Label ID="uploadInfoLbl" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
Here's the code behind file event for button:
protected void uploadMoreClicked(object sender, EventArgs e)
{
int countFiles = 0;
if (moreUpload1.HasFile)
{
moreUpload1.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload1.FileName);
string fn2 = moreUpload1.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
if (moreUpload2.HasFile)
{
moreUpload2.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload2.FileName);
string fn2 = moreUpload2.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
if (moreUpload3.HasFile)
{
moreUpload3.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload3.FileName);
string fn2 = moreUpload3.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
if (moreUpload4.HasFile)
{
moreUpload4.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload4.FileName);
string fn2 = moreUpload4.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
uploadInfoLbl.Text = countFiles + " file(s) uploaded<br/>";
}
But button click event doesn't work. Please suggest me what i am doing wrong. Thanks in Advance!
I would like to take all information stored in a repeater and place it in the body of an email message for sending. Basically, it's a product order form (which also makes use of a repeater) that sends users to an order review page with a form at the bottom that allows them to send the order information to someone else. I am allowed to set up the order information as a table. I have everything working, and my code successfully sends emails. However, I am not sure how to pull the order review repeater's contents into the message body for an email.
Any suggestions/tips are appreciated! Thanks!
Designer code:
<asp:Repeater ID="orderRepeater" runat="server" >
<itemtemplate>
<%# Eval("LocationName") %>
<div class="headerRow">
<div class="header">
<div class="thumb">
<p></p>
</div>
<div class="headerField name"><p class="hField">Product</p></div>
<div class="headerField sku"><p class="hField">GOJO SKU</p></div>
<div class="headerField size"><p class="hField">Size</p></div>
<div class="headerField case"><p class="hField">Case Pack</p></div>
<div class="headerField qty"><p class="hField">Quantity</p></div>
</div>
</div>
<div class="table">
<div class="row">
<div class="thumb"><%# Eval("Thumbnail") %></div>
<div class="field name"><p class="pField"> <%#Eval("ProductName") %> </p></div>
<div class="field sku"><p class="pField"> <%#Eval("Sku") %></p></div>
<div class="field size"><p class="pField"> <%#Eval("Size") %></p></div>
<div class="field case"><p class="pField"><%#Eval("CasePack") %></p></div>
<div class="field qty"><p class="pField"><%#Eval("Qty") %></p></div>
</div>
</div>
</itemtemplate>
</asp:Repeater>
<asp:placeholder id="form" runat="server">
<asp:label id="msgLbl" runat="server" text=""></asp:label>
<asp:hyperlink id="link" runat="server" visible="false" NavigateUrl="/united-states/market/office-buildings/obproductmap/ProductList" >Product Listing</asp:hyperlink><br />
<asp:hiddenfield id="emailTbl" runat="server"></asp:hiddenfield>
<div id="emailForm">
<asp:ValidationSummary ID="vsEmailForm" runat="server" ForeColor="red" DisplayMode="BulletList" /><br />
<div id="yourFields">
<div id="yNameInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvYName" ForeColor="red"
ControlToValidate="yName" errormessage="You must enter your name" Text="*"
Display="Dynamic" SetFocusOnError="True"></asp:requiredfieldvalidator>
Your Name:<br /> <asp:TextBox runat="server" id="yName" size="40"></asp:TextBox>
</div>
<div id="yEmailInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvYEmail" ForeColor="red"
ControlToValidate="yEmail" Display="Dynamic"
errormessage="You must enter your email" Text="*" SetFocusOnError="True"></asp:requiredfieldvalidator>
<asp:regularexpressionvalidator runat="server" id="revYEmail" ForeColor="red"
ControlToValidate="yEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
errormessage="Your email address is not valid. Please try again." Text="*"
Display="Dynamic" SetFocusOnError="True"></asp:regularexpressionvalidator>
Your Email: <br /> <asp:TextBox runat="server" id="yEmail" size="40"></asp:TextBox><br /><br />
</div>
</div>
<div id="reFields">
<div id="rNameInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvRName" ForeColor="red"
ControlToValidate="rName" Text="*"
errormessage="You must enter a recipient's name" Display="Dynamic"
SetFocusOnError="True"></asp:requiredfieldvalidator>
Recipient's Name: <br /><asp:TextBox runat="server" id="rName" size="40"></asp:TextBox>
</div>
<div id="rEmailInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvREmail" ForeColor="red"
ControlToValidate="rEmail" Display="Dynamic" Text="*"
errormessage="You must enter a recipient's email" SetFocusOnError="True"></asp:requiredfieldvalidator>
<asp:regularexpressionvalidator runat="server" id="revREmail" ForeColor="red"
ControlToValidate="rEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
errormessage="The recipient's email address is not valid. Please try again."
Text="*" Display="Dynamic" SetFocusOnError="True"></asp:regularexpressionvalidator>
Recipient's Email:<br /> <asp:TextBox runat="server" id="rEmail" size="40"></asp:TextBox><br /><br />
</div>
</div>
<div id="buttons">
<asp:Button id="submit" Text="Submit" runat="server" CausesValidation="true"
onclick="submitBtn" />
<asp:Button id="cancel" Text="Cancel" runat="server" CausesValidation="false" /><br /><br />
<asp:Button id="print" Text="Print" runat="server" CausesValidation="false "/>
<asp:Button id="pdf" Text="Save as PDF" runat="server" CausesValidation="false" />
</div>
</div>
</asp:placeholder>
<asp:placeholder id="sentMsg" visible="false" runat="server">
<asp:Label id="lbl" runat="server" Text="Your message has been sent!"></asp:Label>
</asp:placeholder>
Code behind:
protected void getOrder(Item CurrentItem)
{
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (Session["orderComplete"] != null && Session["orderComplete"] != "")
{
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoOrderReview']");
Database db = Sitecore.Context.Database;
DataSet dset = new DataSet();
if (ProductGroup != null)
{
string InFromSession = Session["orderComplete"].ToString();
try
{
DataTable summary = dset.Tables.Add("summary");
summary.Columns.Add("LocationName", Type.GetType("System.String"));
summary.Columns.Add("Thumbnail", Type.GetType("System.String"));
summary.Columns.Add("ProductName", Type.GetType("System.String"));
summary.Columns.Add("Sku", Type.GetType("System.String"));
summary.Columns.Add("Size", Type.GetType("System.String"));
summary.Columns.Add("CasePack", Type.GetType("System.String"));
summary.Columns.Add("Qty", Type.GetType("System.String"));
summary.Columns.Add("Location", Type.GetType("System.String"));
Label qL = (Label)FindControl("qty");
string[] orders = InFromSession.Split(';');
string tempheader = "";
foreach (string order in orders)
{
DataRow drow = summary.NewRow();
if (order != "")
{
string[] things = order.Split(',');
string skus = things.GetValue(0).ToString();
if (skus != "")
{
Item locName = db.Items[skus];
Item LocationItem = ScHelper.FindAncestor(locName, "gojoProductLocation");
if (LocationItem != null)
{
string LocationName = LocationItem.Fields["Header"].ToString();
if (tempheader != LocationName)
{
drow["LocationName"] = "<div><h1>" + LocationName + "</h1></div>";
tempheader = LocationName;
}
}
}
}
string purchase = order;
int total = orders.GetUpperBound(0);
if (purchase != "")
{
string[] infos = purchase.Split(',');
string ids = infos.GetValue(0).ToString();
string qtys = infos.GetValue(1).ToString();
if (ids != "")
{
Item anItem = db.Items[ids];
Item orderItem = db.Items[anItem.Fields["Reference SKU"].Value];
if (orderItem != null)
{
Item marketItem = db.Items[orderItem.Fields["Master Product"].Value];
if (marketItem != null)
{
Item CPNItem = db.Items[marketItem.Fields["Complete Product Name"].Value];
drow["Thumbnail"] = "";
Sitecore.Data.Fields.XmlField fileField = marketItem.Fields["Thumbnail"];
drow["Thumbnail"] = "<image src=\"" + ScHelper.GetCorrectFilePath(fileField) + "\" border=\"0\" alt=\"\">";
if (CPNItem != null)
{
var name = CPNItem["Complete Name"];
drow["ProductName"] = name;
}
drow["Sku"] = marketItem.Fields["SKU"].Value;
drow["CasePack"] = marketItem.Fields["Case Pack"].Value;
if (marketItem.Fields["Size"] != null)
{
drow["Size"] = marketItem.Fields["Size"].Value;
}
else
{
drow["Size"] = "N/A";
}
drow["Qty"] = qtys.ToString();
summary.Rows.Add(drow);
}
}
}
}
}
orderRepeater.DataSource = dset;
orderRepeater.DataMember = "summary";
orderRepeater.DataBind();
}
catch (Exception x)
{
//
}
}
}
}
else
{
HyperLink none = (HyperLink)FindControl("link");
Label msg = (Label)FindControl("msgLbl");
none.Visible = true;
msg.Text = "You have not selected any items for purchase. To purchase items, please visit our complete product listing: ";
}
}
protected void sendEmail()
{
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoOrderReview");
if (HomeItem != null)
{
TextBox rTxt = (TextBox)FindControl("rEmail");
TextBox fName = (TextBox)FindControl("yName");
try
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.To.Add(rTxt.Text);
msg.Subject = "GOJO product order summary";
msg.From = new System.Net.Mail.MailAddress("donotreply#GOJO.com");
msg.Body = "Here is a list of the products your friend, " + fName.Text + ", has selected: ";
msg.IsBodyHtml = true;
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient("mail.innismaggiore.com");
sc.Send(msg);
}
catch (Exception EX)
{
GOJOHelper.WriteLog("GOJO Order Review - sendEmail()", EX.ToString());
}
}
}
protected void submitBtn(object sender, EventArgs e)
{
if (Page.IsValid)
{
Database db = Factory.GetDatabase("master");
PlaceHolder form = (PlaceHolder)FindControl("form");
PlaceHolder sent = (PlaceHolder)FindControl("sentMsg");
using (new SecurityDisabler())
{
sendEmail();
form.Visible = false;
sent.Visible = true;
}
}
}
}
I think this answer has what you're looking for. Basically, you can use javascript to send the html to the server in order to include it in your email:
asp.net get html controls in code behind
Also, make sure you include a ValidateRequest="false" on the page in order to post back html
if someone else has same problem and the repeater object has no image this solution is simple and easy instead of trust to a client javascript feedback !!
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =new HtmlTextWriter(stringWrite);
Repeater1.RenderControl(htmlWrite);string emailContent = stringWrite.ToString();