MVC WebForms Controls and Events - c#

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.

Related

How to call a C# application from outside using JavaScript?

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)
{
...
}

Adding a ASP Control to page from Code Behind within InnerHTML

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.
}

JQuery UI and DataTables

over the past few weeks I've been putting together a c# application with heavy use of JQuery UI coupled with the DataTables.net table functionality. I have a quick question regarding session detection.
Now, i have detection in my Page_Load to check for session variables being present etc, but this doesn't prevent an end-user from clicking on tabs, and entering text client side.
So, my question is what is the best way to handle session variables, when using client side scripting like that of JQuery etc?
EDIT
What i'm trying to prevent from happening, is the end user trying to use the Filtering options of DataTables against a page that needs refreshing. For example, at the moment, my page just sits there with the processing dialog - it's not until they either move to another page within the site, or hit the refresh Data button that they are redirected to the main login stage.
I guess, i'm looking for something, like checking for session login = true, when client side activity is performed.
You can define some public variable in your .cs file and use it in your .aspx file.like this :
Server Side :
public partial class WebForm2 : System.Web.UI.Page
{
public bool sessionSet; // this is your variable
protected void Page_Load(object sender, EventArgs e)
{
}
}
Client Side :
<div
<%if (!sessionSet)
{
%>
style="display:none"
<%
} %>
>
</div>
After checking session if the session not setted client will see this in page source:
<div style="display:none"></div>

Add html layout to a blank aspx page

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....

ASP.Net Label change in C#

I am usually dealing with c# code , but recently developing a asp.net page , I have a Calendar that Appears and the user selects the date he/she wants. On that page is a asp lbl that i would like to display the currently selected date, which is normally easy for me but i am having trouble referencing/finding the control . Also I am unsure of the best way to do achieve this and i'm sure to come across this problem in the future.
This is where I would like to set the lbl text and have tried using the FindControl method but it's not working for me , thinking its possibly nested as i have some divs?.
public void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
Control Lbl = FindControl("inputField");
if (Lbl != null)
{
//Control mycontrol2 = Lbl.Parent;
Lbl.Text = Calendar1.SelectedDate.ToShortDateString();
}
and this is in asp.
<div id="date">
<input type="text" size="12" id="inputField" />
<script>
$("#inputField").click(function () {
$("#box").show("slow");
});
</script>
</div>
How do I accomplish setting the inputfield text to the Calendar.SelectedDate ?.
(and any tips you have come across yourself if any, for good practice)
Thanks For any help.
Any reason why you're not using an asp:Label? You can't find the "label" because it is an html control, aka a client side control. Use an <asp:Label id="lblCal" runat="server"... and you should have no problem changing its text in code behind:
lblCal.Text = Calendar1.SelectedDate.ToShortDateString();
Asp.Net considers only server tags as being controls available at C# level.
All those DIVs and other tags are just plain text for the Asp.Net, they will no be considered in the control hierachy.
To make Asp.Net consider it in the server, place the runat="server" attribute on the tags of your interest. They will become accessible in the code-behind by the name placed in the id attribute.
Asp.Net will never be abled to find the 'inputField' in your sample code.
Solution:
To solve your problem I recommend you use an Asp.Net WebForm control called TextBox... if what you want is an input:
<asp:TextBox runat="server" id="inputField" />
By doing this, you will be abled to access the inputField, in the code-behind by name:
inputField.Text = Calendar1.SelectedDate.ToShortDateString();

Categories

Resources