I am trying to create a basic macro that encapsulates a form and the ability to email the details entered into it. It works fine for Textboxes, but for some reason the DropDownLists take the first value in the list of options. I've been working on this for hours and seem to've tried everything, so hopefully someone can suggest a solution. I am using Umbraco 4.0.3 and unfortunately upgrade is not an option. My reduced code is as follows:
CorpRefundForm.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="CorpRefundForm.ascx.cs" Inherits="umbracowebsitewizard_site.Usercontrols.CorpRefundForm" %>
<asp:DropDownList ID="frm_dropdown" runat="server" CssClass="linkselect" />
<br />
<button id="submitButton" runat="server" onserverclick="submitButton_Click">Submit</button>
CorpRefundForm.ascx.cs
using System;
using System.Net.Mail;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace umbracowebsitewizard_site.Usercontrols
{
public partial class CorpRefundForm : UserControl
{
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
frm_dropdown.Items.Add(new ListItem("Select one", ""));
frm_dropdown.Items.Add(new ListItem("One", "One"));
frm_dropdown.Items.Add(new ListItem("Two", "Two"));
frm_dropdown.Items.Add(new ListItem("Three", "Three"));
frm_dropdown.Items.Add(new ListItem("Four", "Four"));
}
}
public void submitButton_Click(object sender, EventArgs e)
{
SmtpClient mySMTPClient = new SmtpClient();
mySMTPClient.Send("[email removed]", "[email removed]", "Test", frm_dropdown.SelectedValue + frm_dropdown.Text + frm_dropdown.SelectedItem.Value + frm_dropdown.SelectedItem.Text);
}
}
}
CorpRefundForm.ascx.designer.cs:
using System.Web.UI.WebControls;
namespace umbracowebsitewizard_site.Usercontrols
{
public partial class CorpRefundForm
{
protected DropDownList frm_dropdown;
}
}
That probably happens since your first ListItem does not have a Value assigned. Try to assign a value, and see if it works.
frm_dropdown.Items.Add(new ListItem("Select one", "-1"));
Solved it! Turns out the jquery.linkselect-1.2.07.min.js library was doing something with the DropDownList that broke it. Took that out and it worked.
Related
I'm trying to create a dynamic news html page.
The problem occurs when I try to create the html dynamically. I'm new to C#, and don't know what's wrong. Here is my c# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NewsAPI;
using NewsAPI.Models;
using NewsAPI.Constants;
namespace NewsDemo
{
public partial class Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
LoadNewsPage();
}
}
protected void LoadNewsPage()
{
try
{
var newsApiClient = new NewsApiClient("key");
List<string> mylist = new List<string>();
mylist.Add("google-news");
mylist.Add("bbc-news");
mylist.Add("cnn");
mylist.Add("the-new-york-times");
var articlesResponse = newsApiClient.GetTopHeadlines(new TopHeadlinesRequest
{
Sources = mylist,
Language = Languages.EN
});
if (articlesResponse.Status == Statuses.Ok)
{
string resulHtml = "";
resulHtml += "<table>";
foreach (var article in articlesResponse.Articles)
{
resulHtml += string.Format("<tr style='valign:top'>", "");
resulHtml += string.Format("<td width=20%><img src='{0}' width='250px' height='200px'></img></td>", article.UrlToImage);
resulHtml += string.Format("<td width=80%><a href='{0}'><h3>{1}</h3></a>{1}<br>{2}<br>{3}<br><br></td>", article.Url, article.Title, article.Author, article.Description);
resulHtml += string.Format("</tr>", "");
}
resulHtml += string.Format("</table>", "");
Label1.Text = resulHtml;
}
}
catch (Exception ex)
{
throw;
}
}
}
}
Whenever I try to run it, (in VS), Chrome opens and the page never loads. I have no idea what is wrong, as I have a console app that can fetch the news and that works fine.
Any help appreciated.
Thanks!
EDIT
Your comments to my answer helped my understand more.
I think your problem doesn't depend on your code but on a known problem with Chrome+Visual Studio
In short:
Either you can debug with another browser
Or you disable JavaScript debugging
I tested your LoadNewsPage() and it does get HTML just fine.
What seems strange is that you are inserting the HTML into the text of a Label.
Instead of doing that, add this HTML in your markup:
<div id="MyNewsSection" runat="server"></div>
And then replace this
Label1.Text = resulHtml;
with
MyNewsSection.InnerHtml = resulHtml;
Also, as a general debugging help, press F12 when in Chrome: if there are any errors, they will be shown to you.
In this post I wanted to figure out how to create dynamically created textboxes in C# Visual Studio.
Adding additional textboxes to aspx based on xml
However, when I try to call the ID of these dynamically created textboxes later in my code to figure out what text the user entered into them, I am getting an error that says these IDs do not exist in the current context. Does anyone know how I would be able to call these?
credit to Adding additional textboxes to aspx based on xml
Here is my entire code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
namespace WebApplication4
{
public partial class WebForm15 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsCallback)
{
//credit to https://stackoverflow.com/questions/44076955/adding-additional-textboxes-to-aspx-based-on-xml#comment75336978_44078684
const string xml = #"<Number>
<Num>1</Num>
<Num>2</Num>
<Num>3</Num>
</Number>";
XDocument doc = XDocument.Parse(xml);
int i = 0;
foreach (XElement num in doc.Root.Elements())
{
TextBox box = new TextBox
{
ID = "dynamicTextBox" + i,
Text = num.Value,
ReadOnly = false
};
divToAddTo.Controls.Add(box);
divToAddTo.Controls.Add(new LiteralControl("<br/>"));
i++;
}
}
}
protected void BtnGetValues_Click(object sender, EventArgs e)
{
IList<string> valueReturnArray = new List<string>();
foreach (Control d in divToAddTo.Controls)
{
if (d is TextBox)
{
valueReturnArray.Add(((TextBox)d).Text);
}
}
//valueReturnArray will now contain the values of all the textboxes
}
}
}
Here is aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm15.aspx.cs" Inherits="WebApplication4.WebForm15" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="divToAddTo" runat="server" />
<asp:Button runat="server" ID="BtnGetValues" Text="GetValues" OnClick="BtnGetValues_Click" />
</form>
</body>
</html>
Figured it out!!! Here is what I found after scouring the internet for hours
Solution:
When using dynamic controls, you must remember that they will exist only until the next postback.ASP.NET will not re-create a dynamically added control. If you need to re-create a control multiple times, you should perform the control creation in the PageLoad event handler ( As currently you are just creating only for first time the TextBox using Condition: !IsPostabck ). This has the additional benefit of allowing you to use view state with your dynamic control. Even though view state is normally restored before the Page.Load event, if you create a control in the handler for the PageLoad event, ASP.NET will apply any view state information that it has after the PageLoad event handler ends.
So, Remove the Condition: !IsPostback, So that each time the page Loads, The TextBox control is also created. You will also see the State of Text box saved after PageLoad handler completes. [ Obviously you have not disabled ViewState!!! ]
Example:
protected void Page_Load(object sender, EventArgs e)
{
TextBox txtBox = new TextBox();
// Assign some text and an ID so you can retrieve it later.
txtBox.ID = "newButton";
PlaceHolder1.Controls.Add(txtBox);
}
Now after running it, type anything in text box and see what happens when you click any button that causes postback. The Text Box still has maintained its State!!!
I am creating data driven pages using ASP.NET C# and want to dynamically set the page title using code behind
<%# Page Title="" Language="C#" MasterPageFile="~/FLMaster.master" AutoEventWireup="true" CodeFile="legal-expenses-insurance-news-item.aspx.cs" Inherits="legal_expenses_insurance_news_legal_expenses_insurance_news_item" %>
I have tried using the separate title tags lower down in the page but this didn't work either. Can anyone advise how to do this.
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyApplication
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Title = "Title of my page";
}
}
}
You can modify the Page title like above from your aspx.cs (the code behind file).
If you want to do this directly in your .aspx file, try this:
<% this.Title = "Some Title" %>
This works if you correctly set your Language = "C#" in your #Page directive, which I see you did.
Page class reference from MSDN
The Page has a Title property:
protected void Page_Load(object sender, EventArgs e)
{
this.Title = "Title";
}
You should remove the Title="" from the aspx page. It will override the Title set in your code-behind
<%# Page Language="C#" MasterPageFile="~/FLMaster.master" AutoEventWireup="true" CodeFile="legal-expenses-insurance-news-item.aspx.cs" Inherits="legal_expenses_insurance_news_legal_expenses_insurance_news_item" %>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.Title = "Title";
}
}
I know that this is an old thread, but I found that Page.Title couldn't always be overriden, but Page.Header.Title could (mostly)... so my solution for dynamic title tags from the Master codebehind is:
if (Page.Header != null)
{
if (Page.Header.Title == null || !Page.Header.Title.Contains("COMPANYNAME"))
{
var otitle = Page.Header.Title;
if (otitle == null || otitle.Length==0) {
var textinfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;
otitle = textinfo.ToTitleCase(this.Parent.GetType().Name.Replace("_"," ").Replace("aspx",""));
}
Page.Header.Title = "COMPANYNAME" + " - " + otitle;
}
Page.Header.Title = Page.Header.Title.Replace("COMPANYNAME", Auth.getSetting("companyName"));
}
How are checkbox properties retrieved before they are cleared?
I'd like to count the number of checked boxes after clicking "Go!". Instead, after clicking, the boxes (even those that default to selected) are cleared and the count is zero.
Do I need another way of protecting the values from postback?
→
*.aspx
<%# Page Language="C#" Inherits="LunaIntraDB.sandbox" MasterPageFile="~/SiteMaster.master" %>
<%# MasterType VirtualPath="~/SiteMaster.master" %>
<asp:Content ContentPlaceHolderID="HeadContent" ID="HeadContentContent" runat="server">
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" ID="MainContentContent" runat="server">
<asp:CheckBoxList ID="aCheckBoxList" runat="server" >
<asp:ListItem Value="DontCheck" runat="server">1</asp:ListItem>
<asp:ListItem Value="blah" Selected="True" runat="server">2</asp:ListItem>
</asp:CheckBoxList>
<asp:LinkButton ID="goButton" runat="server" Text="Go!" onclick="Clicked" />
</asp:Content>
*.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
using System.Collections;
namespace LunaIntraDB
{
public partial class sandbox : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
debugPrint("Load,beforeAdd");
aCheckBoxList.Items.Add("Added 1");
aCheckBoxList.Items.Add("Added 2");
aCheckBoxList.Items.Add("Added 3");
aCheckBoxList.Items[4].Selected = true;
debugPrint("Load,addedItems");
} else {
debugPrint("PostBack");
}
}
protected void Clicked(object sender, EventArgs e)
{
debugPrint("Button push");
}
/* Print Selected index and a count of selected checkboxes */
protected void debugPrint(String where) {
String count = aCheckBoxList.Items.Cast<ListItem>().Where(n => n.Selected).ToList().Count.ToString();
System.Diagnostics.Debug.WriteLine(where +": "+ aCheckBoxList.SelectedIndex.ToString() + " =>" + count + "/"+ aCheckBoxList.Items.Count.ToString() );
}
}
}
Console output
[0:] Load,beforeAdd: 1 =>1/2
[0:] Load,addedItems: 1 =>2/5
// check a bunch and click "Go!"
[0:] PostBack: -1 =>0/5
[0:] Button push: -1 =>0/5
Mono version
Mono JIT compiler version 3.2.3 (tarball Sun Sep 22 20:38:43 UTC 2013) Copyright (C) 2002-2012 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
TLS: __thread
SIGSEGV: altstack
Notifications: epoll
Architecture: amd64
Disabled: none
Misc: softdebug
LLVM: supported, not enabled.
GC: sgen
Taken from http://www.strawberryfin.co.uk/blog/2012/08/22/dealing-with-dynamic-checkboxlists-losing-their-state-after-postback/
In Page_Load(object sender, EventArgs e):
setCheckBoxStates (aCheckBoxList);
elsewhere
public static void setCheckBoxStates(CheckBoxList cbl)
{
// if we are postback and using mono
if (HttpContext.Current.Request.HttpMethod == "POST" && Type.GetType("Mono.Runtime") != null)
{
string cblFormID = cbl.ClientID.Replace("_","$");
int i = 0;
foreach (var item in cbl.Items)
{
string itemSelected = HttpContext.Current.Request.Form[cblFormID + "$" + i];
if (itemSelected != null && itemSelected != String.Empty)
((ListItem)item).Selected = true;
i++;
}
}
}
Though #Will's answer in on the right track, it isn't conclusive of the entire issue.
For example, when a CheckBoxList is inside of Repeater control, the ClientID has a different format to indicate the CheckBoxList position inside the Repeater.
It's also safe to say that we don't really want to handle this issue for every use of a CheckBoxList, so I've created a custom control that extends the CheckBoxList.OnLoad event to resolve the issue outline above.
namespace YOURNAMESPACE.Controls
{
using System.Text.RegularExpressions;
using System;
using System.Web;
using WebControls = System.Web.UI.WebControls;
public class CheckBoxList : WebControls.CheckBoxList
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (HttpContext.Current.Request.HttpMethod == "POST" && Type.GetType("Mono.Runtime") != null) {
string cblFormID = Regex.Replace(ClientID, #"_\d+$", String.Empty).Replace("_", "$");
int i = 0;
foreach (WebControls.ListItem item in Items)
item.Selected = HttpContext.Current.Request.Form[cblFormID + "$" + i++] == item.Value;
}
}
}
}
you should try EnableViewState="True" property at #page as follow:
<%# Page Language="C#" Inherits="LunaIntraDB.sandbox"
MasterPageFile="~/SiteMaster.master"
EnableViewState="True"
%>
I have solution with two project: one webApplication and one ClassLibrary with edmx and all entity framework logic. This work fine, but if I try to use strongly typed data, it begin the problem.
in code behind I use this function:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;
using System.Web.UI;
using System.Web.UI.WebControls;
using EDMNearClass;
namespace WebSite
{
public partial class dettaglio_prodotto : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Response.Write(Page.RouteData.Values["DESCRIZIONE"]);
}
public IQueryable<ProductRepository.DesTagliaP> GetProduct_Taglie([RouteData("Id")] string itemId)
{
decimal ProdId = decimal.TryParse(itemId, out ProdId) ? ProdId : 0;
ProductRepository pr = new ProductRepository();
var myEnts = pr.taglieProdottiDesGetbyUId(1,ProdId).AsQueryable();
return myEnts;
}
}
}
In aspx part I use this code:
<asp:Repeater ID="rpTaglie" runat="server" ItemType="EDMNearClass.ProductRepository.DesTagliaP" SelectMethod="GetProduct_Taglie">
<ItemTemplate>
<div class="quanitybox">
<label for="qty"><%# Item.Codice %></label>
<asp:TextBox runat="server" ID="quantita" CssClass="input-text qty" />
</div>
</ItemTemplate>
</asp:Repeater>
Intellisense working and help me to choise proprerty of EDMNearClass.ProductRepository.DesTagliaP, but at run time i receive error.
If I use Eavl("Codice") and I remove ItemType="EDMNearClass.ProductRepository.DesTagliaP", all work fine.
I checked on /bin folder and EDMNearClass.dll EDMNearClass.pdb are present and updated.
How can I solve this problem?
Just a guess - but i could imagine the repeater binding not liking IQueryable. I would bind to IEnumerable or just a List. Would something like the following work - not exact just to give you an idea.
public List<ProductRepository.DesTagliaP> GetProduct_Taglie([RouteData("Id")] string itemId)
{
decimal ProdId = decimal.TryParse(itemId, out ProdId) ? ProdId : 0;
ProductRepository pr = new ProductRepository();
var myEnts = pr.taglieProdottiDesGetbyUId(1,ProdId).ToList();
return myEnts;
}
EDIT
I would also try to bind the repeater explicitly to the collection rather than use the select method attribute. See this answer
Using ItemType for strongly typed repeater control?