Unable to create a button in my Class ASP.net - html

So I want to add a asp button after my I create a new instance. I'm having trouble giving the button a name, id, etc. Like so <asp:Button ID="Button1" runat="server" Text="Button" /> I'm unable to do this because everytime I try to add parenthesis " " it won't work. Also, I want to be able to give all the Logs a seperate id for each button created. I'm also having trouble removing the output that its creating in the top left hand side corner, why is this appearing twice? I just want it to appear ONCE in the middle of the page! Keep in mind, I've search alot of places for this but there are no answers. Any help, I will provide all the code below that is need. Thanks!
Class:
public class WelcomeText
{
public string Greet;
public string Name;
public DateTime Visited;
public WelcomeText(string greet, string name, DateTime visited)
{
Greet = greet;
Name = name;
Visited = visited;
}
public void greetUser(string msg)
{
HttpContext.Current.Response.Write(msg + Greet + " " + Name + " " + Visited + "<button></button><br/>");
}
}
HTML:
<body>
<form id="form1" runat="server">
<div>
<section>
<%=displayWelcomeText()%>
</section>
</div>
</form>
</body>
Code behind:
public partial class WebForm1 : System.Web.UI.Page
{
public delegate void greetDel(string msg);
protected void Page_Load(object sender, EventArgs e)
{
// display text
displayWelcomeText();
}
public string displayWelcomeText()
{
string greetString = "";
WelcomeText wT1 = new WelcomeText("Welcome", "Sean", DateTime.Now);
WelcomeText wT2 = new WelcomeText("Hey", "Test", DateTime.Now);
WelcomeText wT3 = new WelcomeText("Hello", "User", DateTime.Now);
greetDel gD1 = new greetDel(wT1.greetUser);
gD1("Log: ");
greetDel gD2 = new greetDel(wT2.greetUser);
gD2("Log: ");
greetDel gD3 = new greetDel(wT3.greetUser);
gD3("Log: ");
return greetString;
}
}
Problem with my code

Oy!! More than a few problems to solve here.
First, you see the output twice because you are calling the method named displayWelcomeText() twice: the first time in the Page load and again from the aspx page-code itself, e.g. <%=displayWelcomeText()%>.
If you were to examine the content sent by the server, you'd notice that the first set of text is being sent BEFORE the initial tag. Then the second set is inside the <div><section> area.
What's wrong with changing the to be a
Then in the page load method...
myPanel.Controls.Add(new Button() { Text=String.Format("{0} {1}, {2:MM/dd/yyyy}", wt.Greet, wt.Name, wt.Visited);
That will accomplish what you say you want to do. Whether that's going to do anything meaningful is another problem to resolve.

Related

Blazor - iterate through EditForm

I am building a (static) website in Blazor.wasm where the users upload some number of files. My intention is then (after all the files have passed some basic checks) to iteratively present a set of fields which the users are asked to complete. Only after they have submitted all the [Required] information and press submit will the next form show up.
I have included a minimal example below.
if (valid_files == numFiles)
{
for (int counter = 0; counter < num_files; counter++)
{
paramList.Add(new ParamsForm { });
<EditForm Model="#paramList[counter]" OnValidSubmit="#SingleSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
Camera type <br>
<InputText id="cameratype" #bind-Value="#paramList[counter].CameraType" />
</p>
<button type="submit">Submit</button>
</EditForm>
}
<button #onclick="HandleValidSubmit">Upload Data </button>
}
The expected behaviour is that on each iteration, a frech instance of the onbject ParamsForm is added to the list. We then create a form based of that instance and wait for the user to complete the form. Once they press the Submit button the next stage of the for loop begins. Once all the data have been submitted and the for loop is completed, the Upload data button should appear and the users are invited to submit all their data to the server.
Instead, none of the code inside the EditForm ... section is being completed. I.e. - I see no popping up of text boxes, and any code that I put in there (for example #Console.WriteLine("This should show up) does not seem to be executed. The Upload data button does not appear and instead an error is thrown complaining that the index is out of range, which is weird because after the code at the top of the for loop there are no longer any elements being accessed by an index.
I am quite new to interacting between c# and HTML, so I think I can appreciate why what I have shouldn't work, but I don't know how I can go about writing something that will work.
Any advice would be gratefully recieved.
The ways of Blazor are a bit mysterious to me, too-- it takes a while to adjust! I do know that Blazor has an OnAfterRender event, which makes me think that it might not like to have user input in a loop like that. Or it may be that it's enumerating if (valid_files == numFiles) as false because those variables aren't initialized yet when the markup first renders.
I'd try two things:
(1) Throw StateHasChanged() at the end of your loop or after the code that sets valid_files and numFiles and see if that does anything you like.
(2) Probably this anyway: instead of looping in the markup, I'd build the entire List<ParamsForm> paramsList in the FileInput's event handler instead, move the counter to the code block, and add counter++ to the end of the SingleSubmit() method.
It's 5:00 am here, just got up to get a snack and going back to bed. Let me know if things still don't fly, and I'll try a more complete example tomorrow. :D
I don't have much information about your class, where you are getting your file list from, and so on. I recommend passing complete objects rather than individual properties. For example, I'd rather have IBrowserFile File {get; set;} in my ParamsForm class than say string FileName. That way, if I decide-- oh, I want to get this or that property-- it's already there.
Anyway, hope something in here might be useful:
#if (CurrentForm is not null)
{
<EditForm Model="CurrentForm" OnValidSubmit="#SingleSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
Camera type <br>
<InputText id="cameratype" #bind-Value="CurrentForm.CameraType" />
</p>
<button type="submit">Submit</button>
</EditForm>
#if (IsComplete) // Don't show upload button until you're done
{
<button #onclick="DoUploads">Upload Data </button>
}
#DisplayMessage
}
#code {
class ParamsForm { public string FileName; public string CameraType; } // Just a placeholder
List<ParamsForm> ParamsList = new List<ParamsForm>();
ParamsForm CurrentForm { get; set; }
int counter = 0;
List<string> FileNames;
bool IsComplete = false;
string DisplayMessage = "";
void InitializeForms()
{
// I don't know your class, so just an example
foreach (var item in FileNames)
{
bool IsValid = false;
// check file validity
if (IsValid) ParamsList.Add(new ParamsForm() { FileName = item });
}
if(ParamsList.Count > 0)
CurrentForm = ParamsList[0];
}
void SingleSubmit()
{
// Do stuff with CurrentForm
if (++counter >= ParamsList.Count) IsComplete = true;
else CurrentForm = ParamsList[counter];
}
async Task DoUploads()
{
// Do stuff with your ParamsList
int UploadCounter = 0;
foreach (ParamsForm item in ParamsList){
DisplayMessage = "Uploading " + UploadCounter + " of " + ParamsList.Count;
StateHasChanged();
// Do the Upload;
}
DisplayMessage = "Finished.";
}
}

Put wizard navbar on top position

I'm working with a wizard component. The navbar is in the botton but my boss wants me to put it in the top of the wizard,I thought that it was an attribute or tag to do it straight forward but I have been reviewing the documentation and I should be wrong (I only found the showNavBar tag).
Is there a way to do it without css or jquery? (we have some problems in the application setting css when working with some components so I would like to avoid it).
Thank you very much
You can achieve this in either of the two ways:
1 - Extending the WizardRenderer
By extending the WizradRenderer you can change the order of the encoding.
In the original Renderer the encodeContent(facesContext, wizard); is called before encodeNavigators(facesContext, wizard); so it's pretty much simple, extend you custom renderer, change the order of the calls.
public class ExNavWizardRenderer extends org.primefaces.component.wizard.WizardRenderer{
#Override
protected void encodeMarkup(FacesContext facesContext, Wizard wizard) throws IOException {
ResponseWriter writer = facesContext.getResponseWriter();
String clientId = wizard.getClientId(facesContext);
String styleClass = wizard.getStyleClass() == null ? "ui-wizard ui-widget" : "ui-wizard ui-widget " + wizard.getStyleClass();
writer.startElement("div", wizard);
writer.writeAttribute("id", clientId, "id");
writer.writeAttribute("class", styleClass, "styleClass");
if(wizard.getStyle() != null) {
writer.writeAttribute("style", wizard.getStyle(), "style");
}
if(wizard.isShowStepStatus()) {
encodeStepStatus(facesContext, wizard);
}
// encode the navigators before the content
if(wizard.isShowNavBar()) {
encodeNavigators(facesContext, wizard);
}
encodeContent(facesContext, wizard);
writer.endElement("div");
}
}
Update your faces-config.xml
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.WizardRenderer</renderer-type>
<renderer-class>com.projectPackage.ExNavWizardRenderer</renderer-class>
</renderer>
</render-kit>
2 - jQuery
In your document.ready you can change the DOM, for example this would do the same as the Renderer:
$('.ui-wizard-step-titles').after($('.ui-wizard-navbar'))

Creating html buttons in code, for table. How to handle server callbacks?

I'm currently working on a project and got stuck. I have a Literal control, placed in my .aspx page and I use a stringbuilder like this to populate it with data :
public string CreateNewEntry(String garageName, String garageType,String garageAdress, String garagePhone, String garageId)
{
StringBuilder sb = new StringBuilder();
sb.Append(#"<tr class=""odd"">");
sb.Append(#"<td class=""v-middle"">");
sb.Append(garageName);
sb.Append(#"</td>");
sb.Append(#"<td class=""v-middle"">");
sb.Append(garageType);
sb.Append(#"</td>");
sb.Append(#"<td class=""v-middle"">");
sb.Append(garageAdress);
sb.Append(#"</td>");
sb.Append(#"<td class=""v-middle"">");
sb.Append(garagePhone);
sb.Append(#"</td>");
sb.Append(#"<td class="""">");
sb.Append(#"<a href=""#"" class=""btn btn-sm btn-icon btn-success"" id=""");
sb.Append("edit"+garageId);
sb.Append(#""" name=""");
sb.Append("edit"+garageId);
sb.Append(#"""runat=""server"" OnServerClick=""processRowButtonClick""><i class=""fa fa-edit""></i></a>");
sb.Append(#"<a href=""#"" class=""btn btn-sm btn-icon btn-danger"" id=""");
sb.Append("delete"+garageId);
sb.Append(#""" name=""");
sb.Append("delete"+garageId);
sb.Append(#"""runat=""server"" OnServerClick=""processRowButtonClick""><i class=""fa fa-ban fa-indent""></i></a></td></tr>");
return sb.ToString();
}
I then run a SQL query, to gather the data and loop trough it with a foreach loop adding all table elements dynamically to the Literal controller.
public void garageViewPopulator()
{
serviceDatabaseDataContext dbQuery = new serviceDatabaseDataContext();
var query = (from GarageDetails in dbQuery.GarageDetails
select GarageDetails);
String _constructorString = "";
NewListEntry tableEntry = new NewListEntry();
foreach (GarageDetail item in query)
{
//Creating new HTML code from the class above
_constructorString += tableEntry.CreateNewEntry(item.garageName.ToString(), item.garageType.ToString(), item.garageAdress.ToString(), item.garagePhone.ToString(), item.garageId.ToString());
}
// My litteral
garageListHolder.Text = _constructorString;
}
I then have a :
protected void processRowButtonClick (object sender, EventArgs e)
{
//Retrieve what button id was pressed, and exec action.
}
In my code-behind file. I assumed this would get called when a user pressed a button in my generated table shown under.
Two questions, is it possible to do it this way? Will the code register the buttons as clickable when i generate them from code? Because right now, clicking them does not execute the current processRowButtonClick function in the code behind.
Secondly, If this is possible, how would I get the name / id of the button pressed? Does anybody have any input?
(It may be easier methods of achieving what I'm trying to do, so I'l be happy to receive information about better solutions as well).

Extract the thread head and thread reply from a forum

I want to extract only the views and replies of the user and the title of the head from a forum. In this code when you supply a url the code returns everything. I just want only the thread heading which is defined in title tag and the user reply which is in between the div content tag. Help me how extract. Explain how to print this in a txt file
package extract;
import java.io.*;
import org.jsoup.*;
import org.jsoup.nodes.*;
public class TestJsoup
{
public void SimpleParse()
{
try
{
Document doc = Jsoup.connect("url").get();
doc.body().wrap("<div></div>");
doc.body().wrap("<pre></pre>");
String text = doc.text();
// Converting nbsp entities
text = text.replaceAll("\u00A0", " ");
System.out.print(text);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
TestJsoup tjs = new TestJsoup();
tjs.SimpleParse();
}
}
Why do you wrapt the body-Element in a div and a pre Tag?
The title-Element can be selected like this:
Document doc = Jsoup.connect("url").get();
Element titleElement = doc.select("title").first();
String titleText = titleElement.text();
// Or shorter ...
String titleText = doc.select("title").first().text();
Div-Tags:
// Document 'doc' as above
Elements divTags = doc.select("div");
for( Element element : divTags )
{
// Do something there ... eg. print each element
System.out.println(element);
// Or get the Text of it
String text = element.text();
}
Here's an overview about the whole Jsoup Selector API, this will help you finding any kind of element you need.
Well I used another code and I collected data from this specific tags.
Elements content = doc.getElementsByTag("blockquote");
Elements k=doc.select("[postcontent restore]");
content.select("blockquote").remove();
content.select("br").remove();
content.select("div").remove();
content.select("a").remove();
content.select("b").remove();

Escape HTML tags in XAML code

How can escape html tags into a xaml code?
For example, if i want to show <b>text</b> in an xaml content to put into a RichTextBox as following:
private void button1_Click(object sender, RoutedEventArgs e)
{
string mystring = "<b>test</b>";
MyRTB.Blocks.Add(Convert(#"<Bold>" + mystring + "</Bold>"));
}
static public Paragraph Convert(string text)
{
String formattedText = ParaHead + text + ParaTail;
Paragraph p = (Paragraph)XamlReader.Load(formattedText);
return p;
}
I tried with multiple combinations of {} and {} and etc but doesnt work, and I dont want use hexa scape if i can do it.
Thanks in advance
You just need to XML-escape it by replacing < with <.
The built-in SecurityElement.Escape or WebUtility.HtmlEncode functions will do that for you.