I have a C# application that uses WebForm. I am using the WebForm to display my application content (HTML / JavaScript).
My question is how do I communicate between them (API)?
Example: I like to minimize the program by using HTML buttons, etc....
If you have a web browser control on top of a normal control you could use the navigation event. E.g. make a link like:
Minimize
And in the navigation event of the browser control (I don't know how the event is actually called - just an example):
public void browser_OnNavigate(object sender, NavigateArgs e)
{
if (e.Target == "#MinimizeWindow")
// minimize and cancel event
else
// navigate to target
}
Local or Remote WebForms Application
You can use AJAX if you are trying to communicate with an external (or local) application.
Local WebForms Application
If by "application" you are actually referring to the back-end (code-behinds, etc.) of your WebForms project, then the other thing to look into are "server tags," otherwise known as "bee-stings." Here are just a few exsamples:
<% %>
<%-- --%>
<%# %>
<%= %>
Additionally, you can use event handlers for things like server-side button or anchor clicks, dropdownlist value changes, etc. You can make standard HTML controls server-side by adding the runat="server" attribute, or you can use .NET's WebControls (though they will still have to have the runat="server" attribute). Examples of these would be:
Front End
<button runat="server" onserverclick="btn_click">Click me</button>
...
or
...
<asp:Button runat="server" OnClick="btn_click">Click me</asp:Button>
Back End
protected void btn_click(object sender, EventArgs e)
{
...
}
Related
Hello,
I know razor is different from webforms but i don't want to mix a lot too.
I created ASP.NET MVC WebForms with Masterpages includes Pages and UserControls. It's working fine but i would like to know about how to handle click events in MVC Webforms?
Codebehind file is still there for example default.aspx.cs, if i can double click on button then it creates click event but not working.
Can we use asp.net components in MVC? What about Code Behind file?
(Example Controls: asp:label, asp:textbox, asp:hyperlink etc.)
Thanks,
UPDATE
This is sample code (contact.aspx):
<div class="contact_text">
<asp:Label ID="lbl_namesurname" runat="server" Text="<%$ Resources:contact, lbl_namesurname.Text%>"></asp:Label>
</div>
<div class="txt_namesurname">
<asp:TextBox ID="txt_namesurname" runat="server" ValidationGroup="contact"></asp:TextBox>
</div>
<div><asp:Button ID="btn_send" runat="server" CssClass="btn_send" Text="<%$ Resources:contact, btn_send.ToolTip%>" ToolTip="<%$ Resources:contact, btn_send.ToolTip%>" OnClick="btn_send_Click" ValidationGroup="contact"/></div>
contact.aspx.cs file:
public partial class contact : ViewPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_send_Click(object sender, EventArgs e)
{
//old code-behind is not working in mvc
}
}
}
There is no such thing as MVC Web Forms. There is ASP.NET MVC and ASP.NET Web Forms. Different technologies, and you can't mix them (though they can sit alongside each other).
MVC does not have the same lifecycle as Web Forms, and therefore you cannot have a code behind or User Controls. MVC must be thought about differently: a request gets routed to a controller. The controller examines the request, makes any calls to a data retrieval layer that it needs to, chooses a view, and passes any necessary data to that view, which is rendered to HTML and sent to the client. Subsequent communication goes through that same process, unless you use AJAX or similar technologies.
So, think about what that button would be doing. Is it supposed to send an email? Then it should be a form submission. Is it supposed to gather some more data and update the DOM on the already loaded page? Then AJAX is probably more appropriate.
I'm trying to add a button to the webpage, from the code behind. I have a single empty div on my main page that visible on and off, when needed. However the content I wish to create dynamically as the div content can change dependent on conditions.
I have realised that within my ASP Control I use a / (backslash) which cancels out my HTML. The problem I now have is understanding how I can get around this with code, is there a way to add ASP Controls to the web page? I am open to suggestions outside of the InnerHtml.
I'm creating my Button like so (in my Code Behind):
string buttonout = string.Format("<asp:Button ID=\"helpButton_0\" CommandArgument=\"0\" CssClass=\"HelpButton\" runat=\"server\" Text=\"?\"/>");
innercontent[0] = string.Format("<table><tr><td>Lead Passenger Information</td></tr><tr><td>Here by deafaul we used your detaisl from your profile, if you're not the lead passenger (As in you're booking for someone else) then please change details.</td></tr><tr><td>{0}</td></tr></table>"+ buttonout);
As Said above, The reason this doesn't work is because of InnerHtml hating backslashes, I think.
I do have a solution to this; and that's by adding more divs to the page.
<div id="HelpBoxDiv" runat="server" Visible="false">
<div id="HelpBoxDiv_Top" runat="server" Visible="true">
</div>
<div id="HelpBoxDiv_Bottom" runat="server" Visible="true">
<asp:Button ID="button_HelpBox_false" runat="server" />
</div>
</div>
I would then add my Innerhtml to the _Top Div, instead of the HelpBoxDiv which I am currently doing now. However this solution doesn't teach me anything.
I am hesitant to ask questions here, as I know a lot of question have been asked and I am sure this one has before, but I didn't find a solution. Any help is much appreciated.
Thank you.
I have realised that within my ASP Control I use a / (backslash) which
cancels out my HTML. The problem I now have is understanding how I can
get around this with code, is there a way to add ASP Controls to the
web page? I am open to suggestions outside of the InnerHtml.
You cannot add ASP.Net server control like a literal string.
Instead, you want to add the dynamic server control to the following approach -
ASPX
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
Code Behind
protected void Page_Init(object sender, EventArgs e)
{
var button = new Button
{
ID = "helpButton_0",
CommandArgument = "0",
CssClass = "HelpButton",
Text = "?"
};
button.Command += button_Command;
PlaceHolder1.Controls.Add(button);
}
private void button_Command(object sender, CommandEventArgs e)
{
// Handle dynamic button's command event.
}
So in ASP.NET I would simply do this:
<asp:ListBox OnSelectedIndexChanged="UpdateModels" runat="server" > </asp:ListBox>
But my listbox is inside an .ascx file. which is registered and included in my actual webpage massupdate.aspx like this
<%# Register TagPrefix="mass" TagName="make" Src="~/DynamicData/Make.ascx" %>
<mass:make id="makeControl" runat="server"/>
and in my make.ascx.cs I have this
public ListBox getlistbox()
{
return DropDownList1;
}
So I have access to the original listbox, but I don't know how to replicate the first code snippet in C# in my codebehind for mass.update.aspx .
First of all, the event registered in the ascx should fire even though it is registered as a control onto the page. Events should bubble up (or maybe down?) through all of the controls on a page, that's part of the "magic" of webforms.
Secondly, if you do need to set an event handler in code, you can either google "add event handler .NET control" or you can type something similar below and Visual Studio intellisense should auto complete it for you after you type the "+=" and you can take it from there.
makeControl.getlistbox().OnSelectedIndexChanged += this.Index_Changed
void Index_Changed(Object sender, EventArgs e) {
// whatever you need to do on the event
}
Want to create dynamic html layout without any asp controls. Actually I want to leave on aspx page only the first line
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Kletka._Default" %>
and the generate full html layout on codebehind. Advise pls how to implement this.
One way is this:
protected void Page_Load(object sender, EventArgs e)
{
string coolHTML = #"<div class=""someclass"">... and other cool content</div>";
Response.Write(coolHTML);
}
With that said. This is a terrible idea. Constructing HTML dynamically on code behind is a nightmare to maintain, it doesn't perform as best as it can and you lose many other features that asp.net offers, which are the main reason to use ASP.NET in the first place.
What you can do is create User controls for specific things (footer, header, left panel, etc) and define a layout for them in markup; then on Code behind, you can add them to specific place holders in the page, depending on some business conditions.
Assuming you have a master page (or at least some content place holders in the page) as so:
<asp:ContentPlaceHolder id="footer" runat="Server" />
On code behind you can do:
footer.Controls.Add(new FooterControl());
Update OP just mentioned in the comments that he doesn't like asp.net controls...
You don't have to use ASP.NET controls, you can use regular HTML controls and set their runat="server" attribute if you need to be able to manipulate their properties on server-side. For example:
<div id="mydiv" runat="server" > some content </div>
On Code behind:
myDiv.Attributes.Add("class","css_class");
myDiv.Attributes.Add("onclick","callJavascriptFunction();");
// and so on.
It's okay to do this sort of thing occasionally under very specific circumstances but I'd avoid this sort of code because is difficult to maintain. Imagine you need to add another class to the myDiv element, for example. Now, you'd have to change you code as opposed to just changing your markup...
So...you want to use ASP.NET web forms without using the built in controls like GridView and so on, at all?
You can write your html and use protected properties?
<%= SomeWhereText %?
or to have the FULL html layout in the code behind make a property
protected string MyEntirePage {get;set;}
and build the string in the code behind
MyEntirePage="<h1>Hello</h1><p>body here</p><p>the end</p>";
and write it out in the aspx page via
<%=MyEntirePage%>
Re: "I've got your point, but I really don't like asp.net controls. I'd prefer to use html controls and customize them with js"
Install NancyFx or maybe the old (but still great) WCF Web Api and use something like KnockoutJs, jQuery or Backbone to perform ajax calls for the dynamic content = no asp.net web forms at all. Yay.
You would need to dynamically add the controls in the Page_Init event. So you need a container to hold your HTML, so you should start by adding a Panel to the Page, then the page's controls would get added to the Panel.
Panel pnl = new Panel();
Page.Controls.Add(pnl);
TextBox txt = new TextBox();
pnl.Controls.Add(txt);
etc....
I have a question about creating and managing events inside an ascx custom web control.
I have created a very stupid control consisting in a div containing a asp:Label control, it is a very simple structure:
<div id="mydiv" runat="server">
<asp:Label id="mylabel" text="Text"... />
</div>
That is, very simple.
I would like to add an event: clicked. I want to let the user add this control on the page and attach handlers to this event so that when this control is clicked it is possible to do something. It might seem a strange solution, it's like i'm trying to invent again the button control, that is: my custom button.
Well to fire the event I would like to add a javascript in my div and call a js function that calls, using ajax mechanism, a server side function.
Well how to call a server side function from here. I posted a question about how to call a server side function from a client side one and got some answers (many of them told me to use PageMethods), well it seems that pagemethod does not work, it compiles but when running and clicking on my control and executing the js (in the line PageMethods.mymethod()) here I have an error --> Java script exception: unrecognized method. It seems not finding the PageMethod.
Well, considering my objective, how can I do?
Ah, a solution like: use the click event in the label is not what I want because the click event must fire when I click in the div, consider that I might set a large padding so that a large empty space can provide a large clickable area.
Thanks in advance.
Create a Event in your User Control
E.g: -
public event EventHandler<CustomEventArgs> Click;
and a handler
public void OnClick()
{
if(this.Click !=null)
{
//what ever else you do
this.Click(new CustomEventArgs(...));
}
}
Also handle the mouse click (mouseleftbuttonup) on the User Control (and fire your event from there). i.e.
protected void OnMouseDown(...){ this.OnClick(); }
From the ASP.NET page, you can register the user control event and handle it:
MyControl.Click += new EventHandler<CustomEventArgs>(myctr_click)
protected myctr_click(object sender, CustomEventArgs e){
//do anything
}
PageMethods uses a web service within the page class; I assume you want a postback to the server and process this click in the page, right?
All controls that postback use a __doPostBack('clientid', '') method to postback to the server. Your label would need to do the same. Within the control, the control needs to implement IPostBackEventHandler to process these events, and raise the click event.
Check out this example: http://www.myviewstate.net/blog/post/2009/05/14/Implementing-IPostBackEventHandler-in-an-ASPNET-Control.aspx
I may have misinterpreted your requirements, but can't you just wrap the div in an asp:linkbutton?
<asp:LinkButton ID="lnkSomething" runat="server" OnClick="lnk_something_Click">
<div id="mydiv" runat="server">
<asp:Label id="mylabel" text="Text"... />
</div>
</asp:LinkButton>
and then on the server side:
protected void lnk_something_Click(object sender, EventArgs e)
{
}
As yellowfrog mentioned in the comments, you could then extend this by further wrapping it in an update panel for an async postback.