ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.5 HOSTING - ASPHostPortal :: How to Create Nested WebGrid in ASP.NET MVC6.

clock November 19, 2014 05:51 by author Mark

How to Create Nested WebGrid with Expand/Collapse in ASP.NET MVC6.

Introduction

In this post, I am explain How to Create Nested WebGrid with Expand/Collapse in ASP.NET MVC6.
Steps :

Step - 1 : Create New Project.

  • Go to File > New > Project > Select asp.net MVC6 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

  • Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

  • Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > OK.

In this example, I have used two tables as below

Step-4: Add Entity Data Model.

  • Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
  • A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
  • Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a class for create a view model.

  • 1st : Add a folder.
  • Go to Solution Explorer > Right Click on the project > add > new folder.
  • 2nd : Add a class on that folder
  • Go to Solution Explorer > Right Click on that folder > Add > Class... > Enter Class name > Add.

Write the following code in this class

using System.Collections.Generic;
namespace MVCNestedWebgrid.ViewModel
{
    public class OrderVM
    {
        public OrderMaster order { get; set; }
        public List<OrderDetail> orderDetails { get; set; }
    }
}

Step-6: Add a new Controller.

  • Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-7: Add new action into your controller for show nested data in a webgrid.

Here I have added "List" Action into "Order" Controller. Please write this following code

public ActionResult List()
{
    List<OrderVM> allOrder = new List<OrderVM>();
 
    // here MyDatabaseEntities is our data context
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        var o = dc.OrderMasters.OrderByDescending(a => a.OrderID);
        foreach (var i in o)
        {
            var od = dc.OrderDetails.Where(a => a.OrderID.Equals(i.OrderID)).ToList();
            allOrder.Add(new OrderVM { order= i, orderDetails = od });
        }
    }
    return View(allOrder);
}

Step-8: Add view for the Action & design.

  • Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.

NOTE " Please Rebuild solution before add view

Html Code
@model IEnumerable<MVCNestedWebgrid.ViewModel.OrderVM>

@{
    ViewBag.Title = "Order List";
    WebGrid grid = new WebGrid(source: Model, canSort: false);
}
<div id="main" style="padding:25px; background-color:white;">
    @grid.GetHtml(
    htmlAttributes: new {id="gridT", width="700px" },
    columns:grid.Columns(
            grid.Column("order.OrderID","Order ID"),
            grid.Column(header:"Order Date",format:(item)=> string.Format("{0:dd-MM-yyyy}",item.order.OrderDate)),
            grid.Column("order.CustomerName","Customer Name"),
            grid.Column("order.CustomerAddress","Address"),
            grid.Column(format:(item)=>{
                WebGrid subGrid = new WebGrid(source: item.orderDetails);
                return subGrid.GetHtml(
                    htmlAttributes: new { id="subT" },
                    columns:subGrid.Columns(
                            subGrid.Column("Product","Product"),
                            subGrid.Column("Quantity", "Quantity"),
                            subGrid.Column("Rate", "Rate"),
                            subGrid.Column("Amount", "Amount")
                        )                   
                    );
            })
        )
    )
</div>
Css Code
<style>
th, td {
        padding:5px;
    }
    th
    {
        background-color:rgb(248, 248, 248);       
    }
    #gridT,  #gridT tr {
        border:1px solid #0D857B;
    }
    #subT,#subT tr {
        border:1px solid #f3f3f3;
    }
    #subT {
        margin:0px 0px 0px 10px;
        padding:5px;
        width:95%;
    }
    #subT th {
        font-size:12px;
    }
    .hoverEff {
        cursor:pointer;
    }
    .hoverEff:hover {
        background-color:rgb(248, 242, 242);
    }
    .expand {
        background-image: url(/Images/pm.png);
        background-position-x: -22px;
        background-repeat:no-repeat;
    }
    .collapse  {
        background-image: url(/Images/pm.png);
        background-position-x: -2px;
        background-repeat:no-repeat;
    }
</style>
Write the following Jquery code for make webgrid collapsible
<script>
    $(document).ready(function () {
        var size = $("#main #gridT > thead > tr >th").size(); // get total column
        $("#main #gridT > thead > tr >th").last().remove(); // remove last column
        $("#main #gridT > thead > tr").prepend("<th></th>"); // add one column at first for collapsible column
        $("#main #gridT > tbody > tr").each(function (i, el) {
            $(this).prepend(
                    $("<td></td>")
                    .addClass("expand")
                    .addClass("hoverEff")
                    .attr('title',"click for show/hide")
                );
            //Now get sub table from last column and add this to the next new added row
            var table = $("table", this).parent().html();
            //add new row with this subtable
            $(this).after("<tr><td></td><td style='padding:5px; margin:0px;' colspan='" + (size - 1) + "'>" + table + "</td></tr>");
            $("table", this).parent().remove();
            // ADD CLICK EVENT FOR MAKE COLLAPSIBLE
            $(".hoverEff", this).live("click", function () {
                $(this).parent().closest("tr").next().slideToggle(100);
                $(this).toggleClass("expand collapse");
            });
        });
        //by default make all subgrid in collapse mode
        $("#main #gridT > tbody > tr td.expand").each(function (i, el) {
            $(this).toggleClass("expand collapse");
            $(this).parent().closest("tr").next().slideToggle(100);
        });    
    });
</script>



ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: How to Increase The Overall Performance of ASP.NET 4.5.1 in your App

clock October 1, 2014 07:23 by author Ben

ASP.NET is really a framework for creating net applications created by Microsoft. Initially the technologies. NET is the successor of ASP which is also a computer software product from Microsoft. With .NET ASP gives a platform for developers to design and create dynamic websites and net portals.



You will find certain items that ought to be regarded as when improving the performance from the application in developing a net application. Here are a few of the tips to improve the performance of ASP.NET 4.5.1:

Turn off Session State
Disable session state if you do not need, as this can improve the all round efficiency. By default the session state is always active. However, you'll be able to disable session state for any specific pages.

Turn off Tracing
If tracing is enabled, tracing will add a whole lot of overhead in producing applications. Though tracing is actually a useful function inside the development because it enables developers to track and trace application sequence, tracing may be turned off, unless you want to monitor the trace logging.

Avoid Page Validation Server (Steer clear of Server-side Validation)
Within this case, must be attempted use of client-side validation, not the server side. Server-side validation will consume a lot of sources around the server which can have an effect on application efficiency.

Stay away from Exceptions (Avoid Exceptions)
Exceptions may be 1 of the biggest resource eater which resulted within the lower of web applications and windows applications. Therefore, it is much better to prevent the use and handling of exceptions which can be not beneficial.

Avoid frequent connections for the database (Steer clear of Frequent Calls to Database)
Connections are frequently made for the database can devote time response and resources (resources). This can be avoided by utilizing batch processing. Producing the minimum database connection as a connection is opened and not closed, may cause efficiency slowdown.

Stay away from utilizing Recursive Functions and Nested Loops
To improve application performance, attempt to always steer clear of utilizing nested loops and recursive functions simply because these functions consume a whole lot of memory.

Turn off the View State

In ASP.NET, the default view state will probably be active and will slow down the website. So if you don't use a kind postback, it's much better to disable view state.

Use Caching
Web page caching could be employed to get a particular period of time and towards the required duration will not visit the server and are served from the cache. In the case of static internet pages and dynamic, Partial Caching [Fragment Caching] may be utilized to break into a couple of pages a user control.



ASP.NET 4.5.1 Windows Cloud Hosting - With ASPHostPortal.com :: How to Transferring User Accounts from ASP.NET to MojoPortal

clock April 10, 2014 08:24 by author Kenny

MojoPortal is a free and open source content management system that allows you to maintain your Web site with no HTML coding knowledge. When you need to build a web application you usually have some business functionality in mind but there is always a certain amount of web plumbing that needs to be implemented for things like navigation, authentication of users, security and roles and other things that are needed to support most kinds of business application logic. Sometimes we need to transfer user accounts from existing ASP.NET membership based sites into MojoPortal. So, in this article i will explain about how to transferring user accounts from ASP.NET to MojoPortal.

For the first step, you must set MojoPortal to use plain text passwords.
And then, create a folder on your PC to contain the scripts > in this folder create the following .bat files:

CreateMojoUserTablesXMLFormats.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set database=[Databasename].[Schema].
set switches= -c -x
set formatDir=[Full path to formats directory with trailing slash]
bcp %database%mp_Users format nul %login% %switches% -f
%formatDir%mojoUsers.xml
bcp %database%mp_UserProperties format nul %login% %switches% -f
%formatDir%mojoUserProperties.xml
bcp %database%mp_userRoles format nul %login% %switches% -f
%formatDir%mp_userRoles.xml


ExportASPNETUserData.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set dataDir=[Full path to data directory with trailing slash]
set database=[Databasename].[Schema].
set switches= -k –c
bcp "SELECT 0 AS UserID, 1 AS SiteID, aspnet_Users.Username AS Name,
aspnet_Users.UserName AS LoginName, COALESCE
(aspnet_Membership.Email,aspnet_Users.UserName + '@dummyemail.co.uk' ) AS
Email, aspnet_Membership.LoweredEmail AS LoweredEmail, NULL AS
PasswordQuestion, NULL AS PasswordAnswer, NULL AS Gender,
aspnet_Membership.IsApproved AS ProfileApproved, NULL AS RegisterConfirmGUID,
aspnet_Membership.IsApproved AS ApprovedForForums, 0 AS Trusted, CASE
aspnet_Roles.RoleName WHEN 'xg' THEN 0 ELSE 1 END AS DisplayInMemberList, NULL
AS WebsiteURL, NULL AS Country, NULL AS [State], NULL AS Occupation, NULL AS
Interests, NULL AS MSN, NULL AS Yahoo, NULL AS AIM, NULL AS ICQ, 0 AS
TotalPosts, NULL AS AvatarURL, 0 AS TimeOffsetHours, NULL AS [Signature],
aspnet_Membership.CreateDate AS DateCreated, aspnet_Membership.UserId AS
userGUID, NULL AS Skin, 0 AS IsDeleted, aspnet_Users.LastActivityDate AS
LastActivityDate, aspnet_Membership.LastLoginDate AS LastLoginDate, NULL AS
LastPasswordChangedDate, NULL AS LastLockoutDate, 0 AS
FailedPasswordAttemptCount, NULL AS FailedPwdAttemptWindowStart, 0 AS
FailedPwdAttemptCount, NULL AS FailedPwdAnswerWindowStart,
aspnet_Membership.IsLockedOut AS IsLockedOut, NULL AS MobilePin, NULL AS
PasswordSalt, NULL AS Comment, NULL AS OpenIDURI, NULL AS WindowsLiveID,
'77C33D82-D6F0-49ED-95A7-84C11919AD94' AS SiteGUID, NULL AS TotalRevenue,
userInfo.ForeName AS FirstName, userInfo.Surname AS LastName,
aspnet_Users.Username as Pwd, 1 AS MustChangePassword, NULL AS NewEmail, NULL
AS EditorPreference, '00000000-0000-0000-0000-000000000000' AS EmailChangeGuid,
NULL AS TimeZoneID, '00000000-0000-0000-0000-000000000000' AS PasswordResetGuid
FROM %database%aspnet_Membership INNER JOIN %database %aspnet_Users ON
aspnet_Membership.UserId=aspnet_Users.UserId INNER JOIN %database%userInfo on
aspnet_Membership.UserId=userInfo.userId INNER JOIN
%database%aspnet_UsersInRoles ON
aspnet_Membership.UserId=aspnet_UsersInRoles.UserId INNER JOIN
%database%aspnet_Roles ON aspnet_UsersInRoles.RoleId =
aspnet_Roles.RoleId" queryout %dataDir%lharUsers.txt %switches% %login% -o
output/usersOutput.txt
bcp "select RoleName,UserId from %database%aspnet_Roles INNER JOIN
%database%aspnet_UsersInRoles on
aspnet_Roles.RoleId=aspnet_UsersInRoles.RoleId" queryout
%dataDir%lharUsersRoles.txt %switches% %login% -o output/userRolesOutput.txt
bcp "SELECT newid() AS PropertyID, UserId AS userGUID, [String to use
as MojoPortal PropertyName] AS PropertyName, Title AS PropertyValueString,
NULL AS PropertyValueBinary, GETDATE() AS LastUpdatedDate, 0 AS IsLazyLoaded
FROM %database%UserInfo
UNION ALL
SELECT newid() AS PropertyID, UserId AS userGUID, [String to use as
MojoPortal PropertyName] AS PropertyName, Title AS PropertyValueString,
NULL AS PropertyValueBinary, GETDATE() AS LastUpdatedDate, 0 AS IsLazyLoaded
FROM %database%UserInfo" queryout %dataDir%lharUserProfiles.txt %switches%
%login% -o output/userPropertiesOutput.txt


ImportMojoPortalUserData.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set database=[Databasename].[Schema].
set dataDir=[Full path to data directory with trailing slash]

set switches= -k -R

set formatDir=[Full path to outputs directory with trailing slash]

bcp %database%mp_users IN %dataDir%lharUsers.txt %login% %switches% -f %formatDir%mojoUsers.xml -o output/importUsers.txt

bcp %database%mp_userProperties IN %dataDir%lharUserProfiles.txt %login% %switches% -f %formatDir%mojoUserProperties.xml -o output/importUserProperties.txt

bcp %database%mp_userRoles IN %dataDir%lharUsersRoles.txt %login% %switches% -f %formatDir%mp_userRoles.xml -o output/importUserRoles.txt


Next step is, create the following subdirectories in this folder: data, formats, output.
After create the CreateMojoUserTablesXMLFormats.bat file and the ExportASPNETUserData.bat file, run these program.
Don’t forget to check the output directory for any errors and check the data files have been created and contain the data you expect.
After that, run the ImportMojoPortalUserData.bat. Check the output directory for any errors and check the database tables have the data.
Switch MojoPortal back to using encrypted passwords and the last test a few logins.



Free Trial ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: How to Send Bulk Email Using ASP.Net 4.5

clock April 3, 2014 12:14 by author Kenny

In this article I’m going to explain about how to send bulk email using ASP.Net 4.5. Bulk email software is software that is used to send email in large quantities. Bulk mail broadly refers to mail that is mailed and processed in bulk at reduced rates. The term does not denote any particular purpose for the mail; but in general usage is synonymous with "junk mail". This tutorial we will use ASP.NET Web Page for provide the user interface for your Web applications, Grid View for enables you to select, sort, and edit values of a data source in a table where each column represents a field and each row represents a record, HTML Email Templates and Gmail SMTP Mail Server.

Let’s start to try this tutorial, for the first step you must create a new project.
Click "File" -> "New" -> choose "Project..." and then select web "ASP .Net Web Forms Application". Name it as "Bulk Email".
And now let’s see in the Design page “Default.aspx” design the web page as in the following screen:

This is code for Design Source (Default.aspx):
Default.aspx.cs

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="BulkEmail._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">              
                <h2>Send Bulk email using asp.net</h2>
            </hgroup>
            <p>To learn more about ASP.NET
            </p>
        </div>
    </section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
       <h3>We suggest the following:</h3>
    <asp:Panel ID="Panel1" runat="server" Width="100%" ScrollBars="Horizontal">
    <p>
       <asp:Button ID="btnBind" runat="server" Text="View" OnClick="btnBind_Click" /> <asp:Label
ID="Label1" runat="server" Font-Bold="true" ForeColor="Green" Text="Total
Customers:">   
</asp:Label><asp:Label ID="lbltotalcount" runat="server" ForeColor="Red" Font
Size="Larger"></asp:Label> </p>
        <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
        <asp:GridView ID="grvCustomers" runat="server"></asp:GridView>
    </asp:Panel>
</asp:Content>

In the Web.config file create the connection string as:
Web.config

<connectionStrings>   
<add name="ConnectionString"connectionString="Server=localhost;userid=root;password=;Database=
orthwind"providerName="MySql.Data.MySqlClient"/>      
</connectionStrings>


In the code behind file (Default.aspx.cs) write the code as:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//Using namespaces 
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Data;

namespace BulkEmail
{
    public partial class _Default : Page
    {
        #region MySqlConnection Connection
        MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            Try
            {
                if (!Page.IsPostBack)
                {

                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }
        #endregion
        #region show message
        /// <summary>
        /// This function is used for show message.
        /// </summary>
        /// <param name="msg"></param>
        void ShowMessage(string msg)
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script
language='javascript'>alert('" + msg + "');</script>");
        }       
        #endregion
        #region Bind Data
        /// <summary>
        /// This display the data fetched from the table using MySQLCommand,DataSet and
MySqlDataAdapter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBind_Click(object sender, EventArgs e)
        {
            Try
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand("Select
CustomerID,ContactName,Address,Phone,Email from customers", conn);
                MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                grvCustomers.DataSource = ds;
                grvCustomers.DataBind();
                lbltotalcount.Text = grvCustomers.Rows.Count.ToString();
            }
            catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
            Finally
            {
                conn.Close();

            }
            btnBind.Visible = false;
        }
        #endregion
        #region Bulk email,GridView,gmail
        /// <summary>
        /// this code used to Send Bulk email 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSend_Click(object sender, EventArgs e)
        {
            Try
            {
                lbltotalcount.Text = string.Empty;
                foreach (GridViewRow grow in grvCustomers.Rows)
               {
                    string strCustomerID = grow.Cells[0].Text.Trim();
                    string strContactName = grow.Cells[1].Text.Trim();
                    string strAddress = grow.Cells[2].Text.Trim();
                    string strPhone = grow.Cells[3].Text.Trim();
                    string strEmail = grow.Cells[4].Text.Trim();               

                    string filename = Server.MapPath("~/Event.html");
                    string mailbody = System.IO.File.ReadAllText(filename);
                    mailbody = mailbody.Replace("##NAME##", strContactName);
                    string to = strEmail;
                    string from = "[email protected]";
                    MailMessage message = new MailMessage(from, to);
                    message.Subject = "Auto Response Email";
                    message.Body = mailbody;
                    message.BodyEncoding = Encoding.UTF8;
                    message.IsBodyHtml = true;
                    SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                    System.Net.NetworkCredential basicCredential = newSystem.Net.NetworkCredential("[email protected]", "Password");
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = true;
                    client.Credentials = basicCredential;
                    try
                    {
                        client.Send(message);
                        ShowMessage("Email Sending successfully...!" + strContactName + " &nbsp;");                                           
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(ex.Message);
                    }
                } 
            }
            catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
            Finally
            {
                conn.Close();
            }
        }
        #endregion
    }
}


Finally, Bulk Sending an E-Mail Using ASP.NET 4.5 with HTML Email Templates and Gmail SMTP Mail Server.



ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: Capture images using web camera in ASP.NET 4.5.1

clock March 25, 2014 09:11 by author Kenny

In this article, i'm going to explain about how to integrate a webcam into your web application using ASP.NET 4.5.1. A web camera can capture images at the server end and a web page can display them. It’s very simple for integrate a webcam and capture images in your website that using ASP.NET 4.5.1.

Before it, make sure that your device has Latest Flash player and Web camera.
Let's following these steps:

First, copy the “WebcamResources” into your new application.
After that, add the following code in to your Default.aspx page:
<object width="450" height="200"param name="movie1" value="WebcamResources/save_picture.swf"

embed src="WebcamResources/save_picture.swf" width="45
0"
height="200" >
</object>

This code will place your Flash object into your web page, used to capture the images from the web cam.
Add one more page there with the name ImageConversions.aspx.
Add the following code into ImageConversion.aspx at the page load event:
string str_Photo = Request.Form["image_Data"]; //Get the image from flash file
byte[] photo = Convert.FromBase64String(str_Photo);
FileStream f_s = new FileStream("C:\\capture.jpg", FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter b_r = new BinaryWriter(f_s);
b_r.Write(photo);
b_r.Flush();
b_r.Close();
f_s.Close();


The above code will convert the bytes to an image and will save the image in the c drive.



FreeTrial ASP.NET 4.5.1 Hosting :: How to Make Web Chat Box Using ASP.NET

clock March 19, 2014 07:19 by author Kenny

You can get your chat box on your website using ASP.NET. The advantage of chat box is make websites and web applications more user interactive and provide a dynamic look too. The functionality of chat box in a website is increasing day by day, because it provides some extra functionalities and looks.

Now, we will explain about how to make Chat Box using ASP.NET.
For the first, Open Visual Studio>Create a new page (class file)
And then, Design your chat box (through HTML and CSS).

Coding (as shown below):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Window1.Visible = true;
    }
 
    private string Chat
    {
        get
        {
            if (Application["a"] == null)
                Application["a"] = "";
            return Application["a"].ToString();
        }
        set
        {
           Application["a"] = value;
        }
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        Label1.Text = Chat;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Chat = TextBox1.Text +"<br/>"+ Chat;
    }
}


The chat box code that we explain here is a combination of GAIA Toolkit and Coding. We are doing this coding in C#.

 



ASP.NET 4.5.1 Hosting - ASPHostPortal.com :: How to Create a Sign Up/Registration Page in ASP.NET

clock January 10, 2014 07:17 by author Ben

Here is the simple step to create a sign up/registration page in ASP.NET. Lets check this out :
1. Open the Microsoft Visual Studio
2. Select one New Asp.Net Web application
3. Open the Design Default.aspx page
4. Drag and Drop one DropDown list and button from the Tool box.
5. Add one new item( i.e., New Registration Page) for the Drop down list
6. Procedure for adding items : Right click on the DropDown List and select properties and select items and add NewRegistration in Text Field.
7. Change the properties of the Dropdown list
a.Kept AutopostBack = True;
b.select the SelectedIndexChanged Event for that..
8. Open the code page that is Default.aspx.cs and and create a method in SelectedIndexChanged event of dropdownlist

using System; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Xml.Linq; 
using System.Data.SqlClient; 
 
public partial class Dynamic_controls : System.Web.UI.Page 

    SqlConnection con; 
    SqlCommand com; 
  protected void Page_Load(object sender, EventArgs e) 
    {        
        
    } 
protected void ddlist_SelectedIndexChanged(object sender, EventArgs e) 
    { 
        Createnewaccount();  
    } 

9. Create new methods for Different controls by using the main method(i.e., Createnewaccount)

private void Createnewaccount ()
         {
             CreateDynamicTextBoxes ();
             CreateDynamicTextBoxes1 ();
             CreateDynamicCheckBoxes ();
             CreateDynamicCheckBoxes1 ();
             CreateDynamicRadioButtons1 ();
             BindDropDownLists ();
         }

10. Create all types of dynamic controls

 protected void CreateDynamicTextBoxes ( )
        {
           
            int c = 1 ;
            TextBox [ ] textBoxArr = new TextBox [ c ] ;/ / array of textboxes
            for (int i = 0 ; i < c ; i + + )
            {
                 
                textBoxArr [ i ] = new TextBox ( ) ;
                textBoxArr [ i ] . ID = " txtBox " + i.ToString ( ) ;
                PH_Name.Controls.Add ( textBoxArr [ i ] ) ;
                RequiredFieldValidator reqfldVal = new RequiredFieldValidator ( ) ;
                reqfldVal.ID = " RequiredValidator " + i ;
                reqfldVal.ControlToValidate = " txtBox " + i ;
                reqfldVal.ErrorMessage = " Not Empty " ;
                reqfldVal.SetFocusOnError = true ;
                PH_Name.Controls.Add ( reqfldVal ) ;
            }
        }
        protected void CreateDynamicTextBoxes1 ( )
        {
            int c = 1 ;
            TextBox [ ] textBoxArr1 = new TextBox [ c ] ;/ / array of textboxes
            for (int i = 0 ; i < c ; i + + )
            {
      
                textBoxArr1 [ i ] = new TextBox ( ) ;
                textBoxArr1 [ i ] . ID = " txtBox1 " + i.ToString ( ) ;
                PH_pwd.Controls.Add ( textBoxArr1 [ i ] ) ;
                RequiredFieldValidator reqfldVal1 = new RequiredFieldValidator ( ) ;
                reqfldVal1.ID = " RequiredValidator1 " + i ;
                reqfldVal1.ControlToValidate = " txtBox1 " + i ;
                reqfldVal1.ErrorMessage = " Not Empty " ;
                reqfldVal1.SetFocusOnError = true ;
                PH_pwd.Controls.Add ( reqfldVal1 ) ;
                 
            }
        }
        private void BindDropDownLists ( )
        {
            SqlDataSource sqlDS = new SqlDataSource ( ) ;
            sqlDS.ConnectionString = ConfigurationManager.ConnectionStrings [ " SAMPLE_2 " ] . ToString ( ) ;
            sqlDS.SelectCommand = " Select CountryID , COUNTRY_NAME from countrynames " ;
            PH_country.Controls.Add ( sqlDS ) ;
            DropDownList ddl = new DropDownList ( ) ;
            ddl.ID = " ddlrank " ;
            ddl.DataSource = sqlDS ;
            ddl.DataTextField = " COUNTRY_NAME " ;
            ddl.DataValueField = " CountryID " ;
            PH_country.Controls.Add ( ddI ) ;
            foreach ( Control ctl in PH_country.Controls )
            {
                if ( ctl is DropDownList )
                {
                    ( ctl as DropDownList ) . DataBind ( ) ;
                }
            }
        }
        protected void CreateDynamicCheckBoxes ( )
        {
                   
                CheckBox chk ;
                chk = new CheckBox ( ) ;
                chk.ID = " chkhobbies " ;
                chk.Text = " savings " ;
                chk.AutoPostBack = false ;
                PH_trans.Controls.Add ( chk ) ;
             
        }
        protected void CreateDynamicCheckBoxes1 ( )
        {
           
            int c = 1 ;
            CheckBox [ ] chk = new CheckBox [ c ] ;
            for (int i = 0 ; i < c ; i + + )
            {
                chk [ i ] = new CheckBox ( ) ;
                chk [ i ] . ID = " chkhobbies1 " + i.ToString ( ) ;
                chk [ i ] . Text = " Current" ;
                chk [ i ] . AutoPostBack = false ;
                PH_trans.Controls.Add ( chk [ i ] ) ;
            }
        }
        protected void CreateDynamicRadioButtons ( )
        {
                Male = new RadioButton RadioButton ( ) ;
                Female = new RadioButton RadioButton ( ) ;
                male = new RadioButton ( ) ;
                female = new RadioButton ( ) ;
                male.Text = " Male " ;
                female.Text = " Female " ;
                male.Checked = false ;
                female.Checked = false ;
                male.GroupName = " unknown " ;
                female.GroupName = " unknown " ;
                male.ID = " malegender " ;
                female.ID = " unknown " ;
                male.AutoPostBack = false ;
                female.AutoPostBack = false ;
                PH_gender.Controls.Add ( male ) ;
                PH_gender.Controls.Add (female ) ;
        }
        protected void CreateDynamicRadioButtons1 ( )
        {
            RadioButtonList radio = new RadioButtonList ( ) ;
            radio.ID = " rblRow " ;
            radio.Items.Add ( new ListItem ( " Male " ) ) ;
            radio.Items.Add ( new ListItem ( " Female " ) ) ;
            PH_gender.Controls.Add ( radio ) ;
             
        }
        protected void CreateDynamicPanel ( )
        {
           
            int c = 1 ;
            TextPanel panel = new Panel ( ) ;
            for (int i = 0 ; i < c ; i + + )
            {
                TextPanel.ID = " txtPanel " + i.ToString ( ) ;
                PlaceHolder1.Controls.Add ( TextPanel ) ;
            }
        }

11. Add the following code to store the data in database

protected void btn_submit_Click ( object sender , EventArgs e )
        {
            for (int i = 0 ; i < 1 ; i + + )
            {
                 
                txtvalue string = " txtBox " + i.ToString ( ) ;
                txtvalue1 string = " txtBox1 " + i.ToString ( ) ;
                ddlvalue string = " ddlrank " ;
                chkvalue string = " chkhobbies " ;
                chkvalue1 string = " chkhobbies1 " + i.ToString ( ) ;
                rbvalue string = " rblRow " ;
                 
                TextBox txt = ( TextBox ) PlaceHolder1.FindControl ( txtvalue ) ;
                TextBox txt1 = ( TextBox ) PlaceHolder1.FindControl ( txtvalue1 ) ;
                DropDownList Dddl = ( DropDownList ) PlaceHolder1.FindControl ( ddlvalue ) ;
                CheckBox Dchk = ( CheckBox ) PlaceHolder1.FindControl ( chkvalue ) ;
                CheckBox Dchk1 = ( CheckBox ) PlaceHolder1.FindControl ( chkvalue1 ) ;
                RadioButtonList Drd = ( RadioButtonList ) PlaceHolder1.FindControl ( rbvalue ) ;
                if ( txt ! = null )
                {
                    try
                    {
                        string strText = txt.Text ;
                        strText1 string = txt1.Text ;
                        strddl string = Dddl.SelectedItem.Text ;
                        strchk string = Dchk.Text ;
                        strchk1 string = Dchk1.Text ;
                        strrdb string = Drd.Text ;
                        / / Store value in database textbox Cell
                        con = new SqlConnection ( ConfigurationManager.ConnectionStrings [ " SAMPLE_2 " ] . ToString ( ) ) ;
                        con.Open ( ) ;
                        com = new SqlCommand ( " insert into Dynamic_Form ( UserName , LastName , DropdownlistValue , Chksavings , Chkcurrent , Radiovalue ) values ​​( ' " + strText + " ' , ' " + strText1 + " ' , ' " + strddl + " ' , ' " strchk + + " ' , ' " + strchk1 + " ' , ' " + strrdb + " ' ) " , con ) ;
                        com.ExecuteNonQuery ( ) ;
                        con.Close ( ) ;
                        lbl_error.Text = " Account Successfully Created " ;
                         
                    }
                    catch ( Exception ex )
                    {
                        throw ex ;
                        / / lbl_error.Text = " There is a problem while creating Account " ;
                         
                    }
                }
            }
        }

Now, run your program and see the result :



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in