ascx runat server script - c#

I have default.aspx with a "Submit" Button and a code behind function called as "btn_Submit" which will perform submit action. Once I deploy the application and if there is any logical problem in btn_Submit code, then I can use runat=server script in default.aspx file and I need not go for another deployment.
But When I tried the same for ascx file, it works very well in development environment i.e in VS but when I move the same to Test server, system throws function not defined. I have renamed the existing function name.
So is it possible to add runat=server script and add c# code in ascx file?

Yes it is possible..
You have to surround your code with markup
<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
//hello, world!
}
</script>
Take a look to thisquestion! I think it will help you..
But it is really better to separate your code..

Did you tell the button which method to run on submit? With "auto event wireup" it will try to find a "buttonname_Click" method if you didn't specify anything. If that doesn't exist, you will get an error.
To call a method with a different name, specify that in the OnClick property of the button.

I am not sure why this happened and still was not able to solve it, So redeployed the application :(

Related

How to call javascript function and c# code on asp:button?

When a user clicks a button on ASP.net page, I need to
Save file from asp:fileUpload in a folder on a server - I guess this needs to be done in C#, like in How to correctly use the ASP.NET FileUpload control
Run a javascript function like in How to call javascript function from asp.net button click event
Is there a way to combine C# and Javascript to achieve what I need? If not, how should I do it?
Try using the onClientClick property of the asp:button element.
Ex, on your .aspx file:
<script type="text/javascript">
function myFunction()
{
alert('hi');
}
</script>
...
<asp:button id="Button1"
usesubmitbehavior="true"
text="Open Web site"
onclientclick="myFunction()"
runat="server" onclick="Button1_Click" />
And in your code behind (.aspx.cs)
void Button1_Click (object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
}
}
More info at
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
Note that no JavaScript actually "runs" until the server-side code (C# in this case) has entirely completed and the resulting page is returned to the client. Once that page renders on the client, then JavaScript runs on the client.
So in order to execute your JavaScript code, all you need to do is include it in the page being returned to the client. There are a number of ways to do this, and the options depend on whether you're using WebForms or MVC.
You might use something like RegisterStartupScript in WebForms, for example. Or, you could just have the JavaScript code exist in a PlaceHolder control with Visible=false and only make the control visible in the response which intends the JavaScript code to run. (Roughly the same method is also easily usable in MVC by just wrapping the JavaScript code in a server-side condition to determine whether to render it or not.)
The main thing to remember is that you're not "running the JavaScript code from C#" or anything like that. There's a hard separation between server-side and client-side code. The server-side code ultimately builds the page that it sends back to the client, and that page can include JavaScript code to run on that client.

asp:Button not responding to clicks with OnClick

I seem to be having a problem with my button's OnClick, it doesn't even react at all to the event. It responds to OnClientClick and executes the code, but when I try to relate it o a function in my .aspx.cs class it just ignores it, and it should be executing very simple code (writing to the output debug)
I've checked every other stackoverflow post about this I could find and no one had the same issue.
I know that my Index.aspx is executing the code inside Index.aspx.cs because the Page_Load function is outputting to the debug window, so that's not the problem.
Here's the important code:
<asp:Button ID="btnCreateOrder" runat="server" Text="Create Order" OnClick="btnClick" />
protected void btnClick(object sender, EventArgs e)
{
System.Diagnostics.Debug.Write("Testing3");
}
Like I said the Page_Load function is working fine so it's not an issue of them not being connected.
DIFFERENT PROBLEM IF YOU FEEL SO INCLINED:
While you're reading, I also have a problem of not being able to find objects from my HTML in my CS file.
What I mean by that is, if I reference this label:
<asp:Label ID="testLabel" runat="server" Text="test"></asp:Label>
by saying
testLabel = "Test2";
I get the error "The name 'testLabel does not exist in the current context"
And if I try to reference it by saying this:
Index.testLabel = "Test2";
I get "'MyProject.Views.Home.Index' does not contain a definition for 'testLabel'" even though it clearly does.
Maybe the .designer file is bad.
Try this: delete the .designer.cs file of your .aspx page, right-click on it and select the 'Convert to web application' option.
EDIT: As for the Button event, how did you generate the method stub for the click event? Did you click the button on the designer view twice and the visual studio generated id for you or did you handcoded it?
Try to delete both the button and the button click event, and when you declare the button again, double click it on the designer view.

Creating a C# Module in DNN

I want to embed a C# class in a module so that I can call the functions using buttons and click events. I have no idea how to do this. I've managed to write the class I want to use, but where do I put the code? I created a module in DNN and got this:
<%# Control Language="C#" ClassName="MailingSystem" Inherits="DotNetNuke.Entities.Modules.PortalModuleBase" %>
<h1>Congratulations</h1>
<p>You have successfully created your module. You can edit the source of the module control by selecting the View Source Action from the Action Menu.</p>
<script runat="server">
</script>
I can't put my code in here, I get all sorts of errors about namespaces not allowed, can't import classes with "Using", and so on. So what am I supposed to do? My class is working, I just need to wrap it in a module and put it on a DNN page.
It is better to start with a DotNetNuke Module Template, like this one. It isn't as easy as creating an aspx page.
simply you can double click on design part of the page , then the page load section will be appear in the page and you can put your c# code there.
You may want to do something like this:
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
/// code goes here
}
</script>
If you don't want want to go the whole module template route. Do the following.
Create an webusercontrol (.ascx)
Go to the code behind file (.ascx.cs) and change the class to inherit from DotNetNuke.Entities.Modules.PortalModuleBase (your will need to add DotNetNuke.dll as reference)
Add what ever controls you want to the ascx and attach any event handlers. I prefer to do this in the page init method
In ASCX:
<asp:Button ID="btnButton" Text="Click me" runat="server" />
In Code Behind:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnButton.Click += btnButton_Click;
// OR
btnButton.Click += (sender, e)=> { // Button clicked! Do something };
}
protected void btnButton_Click(object sender, EventArgs e)
{
// Your button has been clicked, Do something
}
Compile code
Get [yourprojectname].dll file from the bin folder of your project and copy it into DNN's bin folder. Then, copy your module control ascx into a dedicated folder in DNN's DesktopModules Folder
Example Path: DesktopModule > YourProjectName > [YourASCXName].ascx
Login to DNN, go to Host>Extensions and click add extension. Go through the wizard making sure to set your extension type to Module (there are many different types of extensions in DNN).
Once added, you will be be taken back to the module extensions page. Scroll down and find your module extension. Click edit, go to module definitions and add a module definition with a meaningful name.
Example: YourProjectNameMainView
Then, add your ASCX file as a view to that module extension. Click save and you are done with setup
You should be able to drop your (VERY BASIC) module on a page and use it!

how to write javascript in asp.net in code behind using C#

How can I write JavaScript code in asp.net in code behind using C#?
For example:
I have click button event when I click the button I want to invoke this java script code:
alert("You pressed Me!");
I want to know how to use java script from code behind.
Actually, this is what you need:
string myScriptValue = "function callMe() {alert('You pressed Me!'); }";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "myScriptName", myScriptValue, true);
Copy all of javascript into string and then register it into your aspx page in code-behind. Then in aspx page, you can call the javascript function whenever you want. You should write this code in Page_Load method in C# page.
Have a look at the ScriptManager class' RegisterClientScriptBlock and RegisterStartupScript methods.
One way to put some javascript onto the page into a specific location do this:
ASP.Net
<script type="text/javascript">
<asp:Literal id="litScript" runat="server" />
</script>
C#
litScript.Text = "alert("Hello!");"
Of course, you can put anything in there, and I'd recommend a javascript library.
Using the Scriptmanager is also an option.
Not an answer, but a suggestion.
Mixing your js within your code-behind can come back to haunt you, I agree with Adrian Magdas.
Anytime you need to make a simple change/update to your javascript you'll have to re-build your project, which means re-deploying instead of simply pushing out a single .js file.
Something like:
btnSomething.ClientClick = "alert('You pressed me!');";
You might also want to read up on the ScriptManager control and outputting blocks of script.
The right answers usually is "You don't". It's better to define your code in a .js file and use jQuery to hook-up the desired events.
$(document).ready(function() {
$('#myBtn').click(function() {
alert('Handler for .click() called.');
});};
If you want to register a script that will be used in connection with an UpdatePanel (AJAX) use ScriptManager class as Sani Huttunen pointed.
Otherwise you should use the class ClientScriptManager (methods Page.ClientScript.RegisterClientScriptBlock or Page.ClientScript.RegisterStartupScript)
As other user pointed, normally registering a script on the code behind can and should be avoided. It's not a very nice practice and you should do it only in cases where you have no other option.
Response.Write("<script language='javascript'>alert('You pressed Me!');</script>");

C# - ASP.NET Button click event not working

I have an ASP.NET (C#) page with some 3rd party controls, some ajaxy stuff and some normal ASP.NET Button controls.
The Button click events do not fire when clicked.
Double-clicking the button in design mode in VS 2008 switches to the code-behind but doesn't create the event handler.
Creating the event handler manually doesn't help.
The whole page is too big to include here, but this is the top bit:
<%# Page Language="C#" MasterPageFile="~/basewidepage2.master" AutoEventWireup="true" EnableEventValidation="false" CodeFile="CompanyCompliance.aspx.cs" Inherits="CompanyCompliancePage" Title="3DSS" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<%# Register Assembly="obout_Grid_NET" Namespace="Obout.Grid" TagPrefix="cc2" %>
<%# Register Src="usercontrols/CalendarEx.ascx" TagName="CalendarEx" TagPrefix="uc2" %>
<%# MasterType VirtualPath="~/basewidepage2.master" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceholder1" runat="Server">
<script type="text/javascript">
// a bunch of function declarations
</script>
...and my button declaration on the page:
<asp:Button ID="LicenseCsvButton" runat="server" Text="Export to CSV" OnClick="LicenseCsvButton_Click" />
...and the code-behind:
protected void LicenseCsvButton_Click(object sender, EventArgs e)
{
// get data
CompanyCompliance cc = new CompanyCompliance(Master.theCompany.ID);
DataTable dt = cc.BusinessLicenses.Tables[0];
// send to browser as download
Tools.SendTableAsCsvToBrowser(Response, dt, "LicenseData");
}
Any ideas? could it be the ajax or something? Maybe the 3rd party "obout" grid control?
Update:
I did fix this a month or two ago, so I came back to this question to answer it for posterity but couldn't remember exactly how I fixed it! (Curse you, old age!) I had some limited success by replacing some of the ASP.NET AJAX controls with jQuery UI ones but I think the real solution was that one of the properties in the one of the tags was pointing to a control that no longer existed.
If you're in this same situation, try that and let me know what works in the comments and I'll post the correct answer.
During debugging, check the CausesValidation property of your button. For some reason, one of my pages had a button defaulting to "True." When I explicitly set it to "False" everything worked.
I know that this should be resolved by now, but just to share - I just had a similar issue. In my case, the problem was that I had a RequiredFieldValidator in a page, that wasn't visible because it was part of a popup. That validator was supposed to be invoked only when clicking its related "Save" button, but since I didn't have any ValidationGroup set, it would prevent the page to submit for any clicked button. Adding a ValidationGroup to the right button resolved the issue.
Experienced the same issue recently - cause was eventually determined to be that the button was disabled by a juavascript method onbeforesubmit (designed to prevent multiple submissions), and unfortunately web forms appears to check the enabled state of the button before it allows the codebehind event to trigger.
I had this problem just now and it was caused by another control having an AutoPostBack="true" which would submit the form before the button had a chance to submit the form to trigger the click event.
Change
CodeFile="CompanyCompliance.aspx.cs"
to
CodeBehind="CompanyCompliance.aspx.cs"
Related question: CodeFile vs CodeBehind
The inherits directive seems to point to a non-existant type.
Take a look in the code behind file of the CompanyCompliance page - ("CompanyCompliance.aspx.cs").
you should find the correct namespace and something like "public partial class xxx" where xxx is the name of the class which should correspond with your inherits directive. maybe you have to fully qualify the name as TJB already stated.
I had a similar issue, and it was really tricky. I recently migrated a VS 2005 ASP.NET 2.0 web forms app to VS 2010 ASP.NET 4.0.
It was difficult to setup and buggy as expected, but the issue of buttons not firing the click event was getting on my nerves.
In the end, it was as simple as not declaring a submit action in the site.master form. I changed:
<FORM runat="server" name="MainForm" method="post" action="Default.aspx" id="m_mainForm" enctype="multipart/form-data">
to
<FORM runat="server" name="MainForm" method="post" id="m_mainForm" enctype="multipart/form-data">
Boom. Problem solved. I hope it saves days of troubleshooting to someone. Sadly, I couldn't find anything about it on the internet by myself.
I had this problem I have changed the Button property "UseSubmitBehavior"=false. Now it is working.
For future answer seekers : If you are assigning the click handler in code behind, make sure that it is not inside an IsPostBack == false check :
void Page_Load (object oSender, EventArgs oEventArgs)
{
if (IsPostBack == false)
{
oButton += new EventHandler(oButton_Click); // does not work
}
oButton += new EventHandler(oButton_Click); // does work
}

Categories