ASP.NET WP – Delete Database Data ”; Previous Next In this chapter, we will be covering how to delete an existing database record. This topic is similar to the previous chapter except that − instead of updating the record, we will delete it. Both deleting and updating processes are almost the same, except that deleting is simpler. This example will also contain two web pages. On the first page, the users will select a record which they want to delete. On the second page, the record to be deleted is then displayed so that the user can confirm that he/she wants to delete that record. How to Delete a Database Record? Let’s have a look into a simple example in which we will delete an existing database record. First of all, we need to create a new CSHTML page. Enter ListCustomersForDelete.cshtml in the Name field and click OK. Now replace the following code in the ListCustomersForDelete.cshtml file. @{ var db = Database.Open(“WebPagesCustomers”); var selectQueryString = “SELECT * FROM Customers ORDER BY FirstName”; } <!DOCTYPE html> <html> <head> <title>Delete a Customer</title> <style> table, th, td { border: solid 1px #bbbbbb; border-collapse: collapse; padding: 2px; } </style> </head> <body> <h1>Delete a Customer</h1> <table> <thead> <tr> <th> </th> <th>First Name</th> <th>Last Name</th> <th>Address</th> </tr> </thead> <tbody> @foreach(var row in db.Query(selectQueryString)){ <tr> <td><a href = “@Href(“~/DeleteCustomer”, row.Id)”>Delete</a></td> <td>@row.FirstName</td> <td>@row.LastName</td> <td>@row.Address</td> </tr> } </tbody> </table> </body> </html> As you can see, the above page is similar to the EditCustomers.cshtml page, the only difference is that instead of displaying an Edit link for each customer. Use the following code to add the Delete link. Once this is done, it will display a Delete link that will help in deleting the selected record. <td><a href = “@Href(“~/DeleteCustomer”, row.Id)”>Delete</a></td> Delete a Customer from the Database We should start with creating a CHTML file as shown in the following screenshot. Enter DeleteCustomer.cshtml in the name field and click OK. Now replace DeleteCustomer.cshtml file with the following code. @{ var db = Database.Open(“WebPagesCustomers”); var CustomerId = UrlData[0]; if (CustomerId.IsEmpty()) { Response.Redirect(“~/ListCustomersForDelete”); } var customer = db.QuerySingle(“SELECT * FROM CUSTOMERS WHERE ID = @0”, CustomerId); if( IsPost && !CustomerId.IsEmpty()) { var deleteQueryString = “DELETE FROM Customers WHERE Id=@0”; db.Execute(deleteQueryString, CustomerId); Response.Redirect(“~/ListCustomersForDelete”); } } <!DOCTYPE html> <html> <head> <title>Delete Customer</title> </head> <body> <h1>Delete Customer – Confirmation</h1> <form method = “post” action = “” name = “form”> <p>Are you sure you want to delete the following Customer?</p> <p>FirstName: @customer.FirstName <br /> LastName: @customer.LastName <br /> Address: @customer.Address</p> <p><input type = “submit” value = “Delete” /></p> </form> </body> </html> Now let’s run the application and specify the following url − http://localhost:36905/ListCustomersForDelete and you will see the following web page. As you can see all the customers from the database and also the Delete link for each customer. Let’s select the Delete link for Kerry Hill and you will see the following page. All the information is displayed for that customer. When you click on the Delete button then this customer will be deleted from the database. Let’s click the Delete button and you will see that it is deleted from the database as shown in the following screenshot. Now the database only has two records. Print Page Previous Next Advertisements ”;
Category: asp.net Wp
ASP.NET WP – Working with Images ”; Previous Next In this chapter, we will discuss how to add and display images on your website. You can add images to your website and to individual pages when you are developing your website. If an image is already available on your site, then you can use HTML <img> tag to display it on a page. Display Image Dynamically Let’s have a look into a simple example by creating a new folder in the project and name it Images and then add some images in that folder. Now add another cshtml file and Name it as DynamicImages.cshtml. Click OK and then replace the following code in the DynamicImages.cshtml file. @{ var imagePath = “”; if (Request[“Choice”] != null){ imagePath = “images/” + Request[“Choice”]; } } <!DOCTYPE html> <html> <body> <h1>Display Images</h1> <form method = “post” action = “”> I want to see: <select name = “Choice”> <option value = “index.jpg”>Nature 1</option> <option value = “index1.jpg”>Nature 2</option> <option value = “index2.jpg”>Nature 3</option> </select> <input type = “submit” value = “Submit” /> @if (imagePath != “”){ <p><img src = “@imagePath” alt = “Sample” /></p> } </form> </body> </html> As you can see, the body of the page has a drop-down list which is a <select> tag and it is named Choice. The list has three options, and the value attributes of each list option has the name of one of the images that has been put in the images folder. In the above code, the list lets the user select a friendly name like Nature 1 and it then passes the .jpg file name when the page is submitted. In the code, you can get the user”s selection from the list by reading Request[“Choice”]. To begin with, it will see if there is any selection then it will set a path for the image that consists of the name of the folder for the images and the user”s image file name. Let’s run the application and specify the following url http://localhost:36905/DynamicImages then you will see the following output. Let’s click on the Submit button and you will see that index.jpg file is loaded on the page as shown in the following screenshot. If you would like to select another photo from the dropdown list, let’s say Nature 2, then click the Submit button and it will update the photo on the page. Upload Image You can display an image dynamically only when it is available on your website, but sometimes you will have to display images which will not be available on your website. So you will need to upload it first and then you can display that image on your web page. Let’s have a look into a simple example in which we will upload image, first we will create a new CSHTML file. Enter UploadImage.cshtml in the Name field and click OK. Now let’s replace the following code in UploadImage.cshtml file @{ WebImage photo = null; var newFileName = “”; var imagePath = “”; if(IsPost){ photo = WebImage.GetImageFromRequest(); if(photo != null){ newFileName = Guid.NewGuid().ToString() + “_” + Path.GetFileName(photo.FileName); imagePath = @”images” + newFileName; photo.Save(@”~” + imagePath); } } } <!DOCTYPE html> <html> <head> <title>Image Upload</title> </head> <body> <form action = “” method = “post” enctype = “multipart/form-data”> <fieldset> <legend> Upload Image </legend> <label for = “Image”>Image</label> <input type = “file” name = “Image” size = “35”/> <br/> <input type = “submit” value = “Upload” /> </fieldset> </form> <h1>Uploaded Image</h1> @if(imagePath != “”){ <div class = “result”><img src = “@imagePath” alt = “image” /></div> } </body> </html> Let’s run this application and specify the following url − http://localhost:36905/UploadImage then you will see the following output. To upload the image, click on Choose File and then browse to the image which you want to upload. Once the image is selected then the name of the image will be displayed next to the Choose File button as shown in the following screenshot. As you can see the that images.jpg image is selected, let’s click on the Upload button to upload the image. Print Page Previous Next Advertisements ”;
ASP.NET WP – Add Search
ASP.NET WP – Add Search ”; Previous Next In this chapter, we will be covering how to add search functionality in your website using the Microsoft Bing search engine. Adding a search functionality to your website is very easy, you can use the Bing helper and specify the URL of the site to search. The Bing helper renders a text box where users can enter a search term. By adding the capability to search, you can also include Internet search results without leaving your site. You can use the Search option in the following ways − Add a Search, the dialog box in which a user can search your site only which makes it easy for users to find content on your site. Add a box that lets the users to easily search the related sites. Add a box that lets users search the Web, but without having to leave your site. This can be done by launching that search in another window. There are two types of search options that you can use in your website. Simple search Advanced search Simple Search In this simple search option, the helper renders a box that includes the Bing search icon which users can click in order to launch the search. In a simple search, the helper will also render radio buttons in which the user can specify whether to search only the specified site or the web in general. When the user submits the search, the simple option just redirects the search to the Bing site − http://bing.com. Then the results will be displayed in a new browser window, like user is searching in the Bing home page. Advanced Search In the advanced option, the helper will render a search box without radio buttons. In this case, the helper gets the search results and then formats and displays them right in that page instead of just redirecting to the Bing site. Let’s have a look into a simple example of search by creating a new CSHTML file. Enter Search.cshtml file in the Name field and click OK. Replace the following code in the Search.cshtml file. <!DOCTYPE html> <html> <head> <title>Custom Bing Search Box</title> </head> <body> <div> <h1>Simple Search</h1> <p>The simple option displays results by opening a new browser window that shows the Bing home page.</p> Search the ASP.NET site: <br/> @Bing.SearchBox(siteUrl: “www.asp.net”) </div> </body> </html> As you can see in the above code, the siteUrl parameter in the @Bing.SearchBox() is optional, which means that you can specify the user has the option of which site to search. If you don’t specify a URL, then Bing will search the web. You can see that we have specified the www.asp.net website, so it will search that site, but if you want to search your own site, then you will need to specify that URL instead of www.asp.net. Let’s run the application and specify the following url − http://localhost:36905/Search and you will see the following output. Let’s enter some text to search in the search box. Press enter and you will see that the Microsoft Bing home page opens in another tab. Print Page Previous Next Advertisements ”;
ASP.NET WP – Programming Concepts ”; Previous Next In this chapter, we will cover programming concepts with ASP.NET Web Pages using the Razor Syntax. ASP.NET is Microsoft”s technology for running dynamic web pages on web servers. The main aim of this chapter is to make you will familiar with programming syntax which you will use for ASP.NET Web Pages. You will also learn about Razor syntax and code that is written in the C# programming language. We have already seen this syntax in the previous chapters, but in this chapter, we will explain the syntax in detail. What is Razor The Razor Syntax is an ASP.NET programming syntax used to create dynamic web pages with the C# or Visual Basic .NET programming languages. This Razor Syntax was in development since June 2010 and was released for Microsoft Visual Studio 2010 in January 2011. Razor is a markup syntax for adding server-based code to web pages. Razor has the power of traditional ASP.NET markup, but is easier to learn, and easier to use. Razor is a server side markup syntax much like ASP and PHP. Razor supports C# and Visual Basic programming languages. Basic Razor Syntax The Razor Syntax is based on ASP.NET and designed for creating web applications. It has the power of traditional ASP.NET markup, but is easier to use, and easier to learn. Razor code blocks are enclosed in @{…} Inline expressions (variables and functions) start with @ Code statements end with semicolon (;) Variables are declared with the var keyword Strings are enclosed with quotation marks C# code is case sensitive C# files have the extension .cshtml Let’s have a look at the following example − <!– Single statement blocks –> @{ var total = 7; } @{ var myMessage = “Hello World”; } <!– Inline expressions –> <p>The value of your account is: @total </p> <p>The value of myMessage is: @myMessage</p> <!– Multi-statement block –> @{ var greeting = “Welcome to our site!”; var weekDay = DateTime.Now.DayOfWeek; var greetingMessage = greeting + ” Today is: ” + weekDay; } <p>The greeting is: @greetingMessage</p> <!DOCTYPE html> <html lang = “en”> <head> <meta charset = “utf-8” /> <title>Welcome to ASP.NET Web Pages Tutorials</title> </head> <body> <h1>Hello World, ASP.NET Web Page</h1> <p>Hello World!</p> </body> </html> As you can see in the above example that inside a code block each complete code statement must end with a semicolon. Inline expressions do not end with a semicolon. Let’s run your application and specify the following url http://localhost:46023/firstpage in the browser and you will see the following output. Variables to Store Data You can store values in a variable, including strings, numbers, and dates, etc. You create a new variable using the var keyword. You can insert variable values directly in a page using @. Let’s have a look at another simple example in which we will store the data in another variable. <!– Storing a string –> @{ var welcomeMessage = “Welcome to ASP.NET Web Pages!”; } <p>@welcomeMessage</p> <!– Storing a date –> @{ var year = DateTime.Now.Year; } <!– Displaying a variable –> <p>Current year is : @year!</p> Let’s run your application and specify the following url http://localhost:46023/firstpage in the browser and you will see the following output. Decisions Making A key feature of dynamic web pages is that you can determine what to do based on conditions. The most common way to do this is with the If and Else statements. Let’s have a look into the Decisions Making code shown in the following program. @{ var result = “”; if(IsPost){ result = “This page was posted using the Submit button.”; } else{ result = “This was the first request for this page.”; } } <!DOCTYPE html> <html> <head> <title></title> </head> <body> <form method = “POST” action = “” > <input type = “Submit” name = “Submit” value = “Submit”/> <p>@result</p> </form> </body> </html> Let’s run your application and specify the following url − http://localhost:46023/firstpage in the browser and you will see the following output. Now let’s click on Submit and you will see that it also updates the message as shown in the following screenshot. Let’s have a look into another example in which we have to create a simple add functionality that lets users enter two numbers, then it adds them and displays the result. @{ var total = 0; var totalMessage = “”; if (IsPost){ // Retrieve the numbers that the user entered. var num1 = Request[“text1”]; var num2 = Request[“text2”]; // Convert the entered strings into integers numbers and add. total = num1.AsInt() + num2.AsInt(); totalMessage = “Total = ” + total; } } <!DOCTYPE html> <html lang = “en”> <head> <title>My Title</title> <meta charset = “utf-8” /> <style type = “text/css”> body { background-color: #d6c4c4; font-family: Verdana, Arial; margin: 50px; } form { padding: 10px; border-style: dashed; width: 250px; } </style> </head> <body> <p>Enter two whole numbers and then click <strong>Add</strong>.</p> <form action = “” method = “post”> <p> <label for = “text1”>First Number:</label> <input type = “text” name = “text1” /> </p> <p> <label for = “text2”>Second Number:</label> <input type = “text” name = “text2” /> </p> <p><input type = “submit” value = “Add” /></p> </form> <p>@totalMessage</p> </body> </html> Let’s run the application and specify the following url − http://localhost:46023/firstpage in the browser and you will see the following output. Now enter two numbers in the mentioned fields as shown in the following screenshot. Click Add and you will see the sum of these two numbers as shown in the following screenshot. Print Page Previous Next Advertisements ”;
ASP.NET WP – Page Object Model ”; Previous Next The most basic object in ASP.NET is the page. You can access properties of the page object directly without any qualifying object. In the previous chapters, we have used some of the properties and methods of page object like Layout, RenderPage and RenderBody. WebPageBase Class is the base class for classes that represent an ASP.NET Razor page. Properties and Methods of Page Object Model Following are some of the most commonly used properties of Page Object. S.No Property & Description 1 IsPost Returns true if the HTTP data transfer method used by the client is a POST request. 2 Layout Gets or sets the path of a layout page. 3 Output Gets the current TextWriter object for the page. 4 Page Provides property-like access to data shared between pages and layout pages 5 Request Gets the HttpRequest object for the current HTTP request. 6 Server Gets the HttpServerUtility object that provides web-page processing methods. Following are some of the most commonly used methods of Page Object. S.No Method & Description 1 ConfigurePage When overridden in a derived class, configures the current web page based on the configuration of the parent web page. 2 DefineSection Called by content pages to create named content sections. 3 ExecutePageHierarchy() Executes the code in a set of dependent web pages. 4 GetOutputWriter Returns the text writer instance that is used to render the page. 5 href Builds a URL using the specified parameters 6 InitializePage Initializes the current page. 7 IsSectionDefined Returns a value that indicates whether the specified section is defined in the page. 8 PopContext Returns and removes the context from the top of the OutputStack instance. 9 PushContext Inserts the specified context at the top of the OutputStack instance. 10 RenderBody() Renders the portion of a content page that is not within a named section (In layout pages) 11 RenderPage(page) Renders the content of one page within another page 12 RenderSection(section) Renders the content of a named section (In layout pages) 13 Write(object) Writes the object as an HTML-encoded string 14 WriteLiteral Writes an object without HTML-encoding it first. Let’s have a look into a simple example of Page property of Page Object which provides property-like access to data shared between pages and layout pages. In this example, we will set the title of the page using the Page.Title property. Here is the implementation of MyLayoutPage.cshtml file in which we have set the page title. @{ Layout = “~/_Layout.cshtml”; page.Title = “Layout Page”; } <h1> H1 Heading from the Layout page </h1> <p> This is the Main Body part from the Layout page</p> Now we need to specify the same page title in the _Layout.cshtml page as shown in the following code. @{ } <!DOCTYPE html> <html lang = “en”> <head> <title>@Page.Title</title> <link href = “@Href(“/Styles/Site.css”)” rel = “stylesheet” type = “text/css” /> </head> <body> @RenderPage(“/Shared/_Header.cshtml”) <div id = “main”>@RenderBody()</div> @RenderPage(“/Shared/_Footer.cshtml”) </body> </html> Let’s run the application and specify the following url − http://localhost:46023/MyLayoutPage then you will see the following page. As you can see the title is now a Layout Page which we have set using the Page property of Page object. Let’s have a look into another simple example in which we will use the Request Property of Page object @{ Layout = “~/_Layout.cshtml”; Page.Title = “Layout Page”; var path = Request.FilePath; var pageUrl = this.Request.Url; } <h1> H1 Heading from the Layout page </h1> <p> This is the Main Body part from the Layout page</p> <a href = “@pageUrl”>My page</a> <p>Page Url: @pageUrl</p> <p>File Path: @path</p> You can get the page”s file path and URL using the Request object of the page. Let’s run your application again and you will see the following output. Print Page Previous Next Advertisements ”;
ASP.NET WP – Discussion
Discuss ASP.NET WP ”; Previous Next This tutorial will give you a fair idea on how to get started with ASP.NET Web pages. Microsoft ASP.NET Web Pages is a free Web development technology that is designed to deliver the world”s best experience for Web developers who are building websites for the Internet. After completing this tutorial, you will have a better understanding of what is ASP.NET Web Pages, why you need it, and of course, you will also learn how to add ASP.NET Web Pages to your project. Print Page Previous Next Advertisements ”;
ASP.NET WP – View Engines
ASP.NET WP – View Engines ”; Previous Next The View Engine in ASP.NET is used to translate our views to HTML and then render them to the browser. By default, ASP.Net supports ASPX and the Razor View Engine. The view engine templates have a different syntax than the implementation. In this chapter, we will discuss the two most important view engines which are − ASPX View Engine also known as Web Form View Engine and Razor View Engine There are many more third-party view engines, like Spark, Nhaml, etc. ASPX View Engine ASPX or Web Form Engine is the default view engine for ASP.NET that is included with ASP.NET MVC from the beginning itself. The syntax used for writing a view with the ASPX View Engine is the same as the syntax used in the ASP.NET web forms. The file extensions are also the same as for ASP.NET web forms (like .aspx, .ascx, .master). ASPX uses “<% = %>” or “<% : %>” to render server-side content. The namespace for Webform Engine is System.Web.Mvc.WebFormViewEngine. ASPX View Engine does nothing to avoid Cross-Site Scripting attacks by default. ASPX View Engine is comparatively faster than Razor View Engine. Razor View Engine Razor Engine is an advanced view engine that was introduced with MVC3. It is not a new language, but it is a new markup syntax. The Razor syntax is based on the C# programming language. The Razor syntax also supports the Visual Basic language, and everything that we will do using C#, you can do all of that in Visual Basic as well. The namespace for Razor Engine is System.Web.Razor. Razor uses the “@” character instead of “<% %>” as used by the ASPX View Engine. The Razor file extension is “cshtml” for the C# language. By default, Razor View Engine encodes html tags or scripts before it’s being rendered to view that avoids Cross-Site Scripting attacks. Razor View Engine is slow as compared to ASPX View Engine. Syntax Differences To understand the syntax difference, let’s have a look into a simple example that is written in both ASPX and Razor view engines. Following is the code snippet for ASPX view engine. <%foreach (var student in Students){ %> <% if (student.IsPassed){ %> <% = student.FirstName%> is going to next grade. <% } else{ %> <% = student. FirstName %> is not going to next grade. <% } %> <% } %> Following is the same example code written in Razor View engine. @foreach (var student in Students){ @if(student.IsPassed){ @student. FirstName is going to next grade. } else { @student. FirstName is not going to next grade. } } If you look at both the above code snippets written in ASPX and Razor syntax, then you can see quite clearly that Razor syntax is clean and simpler as compared to the ASPX syntax. One of the disadvantages of Razor is, it is not supported by visual editors like Dream Viewer. Print Page Previous Next Advertisements ”;
ASP.NET WP – Database
ASP.NET WP – Database ”; Previous Next In this chapter, we will be covering how to create a database in WebMatrix using ASP.NET Web Pages (Razor) and how to display database data in a page. A database contains one or more tables that contain information, like table for Customers information or table for Students. In any given table you have several pieces of information, for example in Customers table there will be their first name, last name, and address, etc. In most database tables, there is a column that contains a unique identifier which is also known as primary key, like a CustomerID, or StudentID, etc. The primary key identifies each row in the table. Create a Database WebMatrix provides tools in which you can easily create a database and then can add tables in that database. The structure of a database is referred to as the database”s schema. Now let’s open the WebMatrix and create a new empty site. Enter WebPagesCustomers in the Site Name field and click Next. In the left pane, click Database as highlighted in the following screenshot. Now you will see that it opens the database related options in the ribbon. Click on the New Database option. You will see that WebMatrix creates a SQL Server database which is a *.sdf file that has the same name as your site WebPagesCustomers.sdf and you can also rename this file as well. Create Table You can easily create a table in the database either by right clicking on Tables in the left pane and then selecting a New Table or you can click on the New Table option in the ribbon. Now you can see that WebMatrix has opened the table designer. Enter the Table Name and then some columns and press Ctrl+S to save as shown in the following screenshot. For ID row set, the Is Primary Key? and Is Identify? options to be changed to Yes (if they are not). Now let’s enter some raw data to work with by clicking on the Data option and then entering some data as shown in the following screenshot. Display Database Data As we have a database and a Customers table and we also have some data in the database. Now we need to display that on the web page from the database. Let’s create a new CSHTML file. Enter ListCustomers.cshtml in the Name field and click OK. Now to retrieve all the customers from the database let’s replace all the code in ListCustomers.cshtml file as shown in the following program. @{ var db = Database.Open(“WebPagesCustomers”); var selectQueryString = “SELECT * FROM Customers ORDER BY FirstName”; } <!DOCTYPE html> <html> <head> <title>Customers List</title> <style> table, th, td { border: solid 1px #bbbbbb; border-collapse: collapse; padding: 2px; } </style> </head> <body> <h1>Customers List</h1> <table> <thead> <tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Address</th> </tr> </thead> <tbody> @foreach(var row in db.Query(selectQueryString)){ <tr> <td>@row.ID</td> <td>@row.FirstName</td> <td>@row.LastName</td> <td>@row.Address</td> </tr> } </tbody> </table> </body> </html> Now let’s run the application and specify the following url − http://localhost:36905/ListCustomers and you will see the list of customers on the web page as shown in the following screenshot. Print Page Previous Next Advertisements ”;
ASP.NET WP – Working with Files ”; Previous Next In this chapter, we will cover how you can work with text files in your website. You can use text files as a simple way to store data for your website. Text files can be in different formats, such as *.txt, *.xml, or *.csv. You can use the File.WriteAllText method to specify the file to create and then write data to it. You can read/write and move data from/to the text file. Write Data to a File Let’s have a look into a simple example in which we will write a student information into a text file. First we need to create a new CSHTML file Enter TextData.cshtml in the name field and click OK to continue. In this example, we will create a simple form in which the user can enter Student information like first name, last name and marks. We also need to create a text file in the App_Data folder with Data.txt name Let’s replace the following code in the TextData.cshtml file. @{ var result = “”; if (IsPost){ var firstName = Request[“FirstName”]; var lastName = Request[“LastName”]; var marks = Request[“Marks”]; var userData = firstName + “,” + lastName + “,” + marks + Environment.NewLine; var dataFile = Server.MapPath(“~/App_Data/Data.txt”); File.WriteAllText(@dataFile, userData); result = “Information saved.”; } } <!DOCTYPE html> <html> <head> <title>Write Data to a File</title> </head> <body> <form id = “form1” method = “post”> <div> <table> <tr> <td>First Name:</td> <td><input id = “FirstName” name = “FirstName” type = “text” /></td> </tr> <tr> <td>Last Name:</td> <td><input id = “LastName” name = “LastName” type = “text” /></td> </tr> <tr> <td>Marks:</td> <td><input id = “Marks” name = “Marks” type = “text” /></td> </tr> <tr> <td></td> <td><input type=”submit” value=”Submit”/></td> </tr> </table> </div> <div> @if(result != “”){ <p>Result: @result</p> } </div> </form> </body> </html> In the code, we have used the IsPost property to determine whether the page has been submitted before it starts processing. The WriteAllText method of the File object takes two parameters, the file name path and the actual data to write to the file. Now let’s run this application and specify the following url − http://localhost:36905/TextData and you will see the following web page. Let’s enter some data in all the fields. Now click on the submit button. As you can see the information is saved, now let’s open the Data.txt file and you will see that data is written to the file. Append Data to an Existing File For writing data to the text file we have used WriteAllText. If you call this method again and pass it with the same file name, then it will overwrite the existing file completely. But in most cases, we often want to add new data to the end of the file, so we can do that by using the AppendAllText method of the file object. Let’s have a look into the same example, we will just change the WriteAllText() to AppendAllText () as shown in the following program. @{ var result = “”; if (IsPost){ var firstName = Request[“FirstName”]; var lastName = Request[“LastName”]; var marks = Request[“Marks”]; var userData = firstName + “,” + lastName + “,” + marks + Environment.NewLine; var dataFile = Server.MapPath(“~/App_Data/Data.txt”); File.AppendAllText(@dataFile, userData); result = “Information saved.”; } } <!DOCTYPE html> <html> <head> <title>Write Data to a File</title> </head> <body> <form id = “form1” method = “post”> <div> <table> <tr> <td>First Name:</td> <td><input id = “FirstName” name = “FirstName” type = “text” /></td> </tr> <tr> <td>Last Name:</td> <td><input id = “LastName” name = “LastName” type = “text” /></td> </tr> <tr> <td>Marks:</td> <td><input id = “Marks” name = “Marks” type = “text” /></td> </tr> <tr> <td></td> <td><input type = “submit” value = “Submit”/></td> </tr> </table> </div> <div> @if(result != “”){ <p>Result: @result</p> } </div> </form> </body> </html> Now let’s run the application and specify the following url http://localhost:36905/TextData and you will see the following web page. Enter some data and click the submit button. Now when you open the Data.txt file then you will see that the data is appended at the end of this file. Read Data from a File To read the data from a file, you can use the File object and then call ReadAllLines(), which will read all the lines from the file. To do so, let’s create a new CSHTML file. Enter ReadData.cshtml in the Name field and click OK. Now replace the following code in the ReadData.cshtml file. @{ var result = “”; Array userData = null; char[] delimiterChar = {”,”}; var dataFile = Server.MapPath(“~/App_Data/Data.txt”); if (File.Exists(dataFile)) { userData = File.ReadAllLines(dataFile); if (userData == null) { // Empty file. result = “The file is empty.”; } } else { // File does not exist. result = “The file does not exist.”; } } <!DOCTYPE html> <html> <head> <title>Reading Data from a File</title> </head> <body> <div> <h1>Reading Data from a File</h1> @result @if (result == “”) { <ol> @foreach (string dataLine in userData) { <li> Student <ul> @foreach (string dataItem in dataLine.Split(delimiterChar)) { <li>@dataItem</li > } </ul> </li> } </ol> } </div> </body> </html> Now let’s run the application again and specify the following url http://localhost:36905/ReadData and you will see the following web page. Print Page Previous Next Advertisements ”;
ASP.NET WP – Getting Started
ASP.NET WP – Getting Started ”; Previous Next In this chapter, we will look at how to start a simple example using ASP.NET Web Pages. To begin with, we will create a new website and a simple web page. How to Create a Blank Website? To start with, launch Microsoft WebMatrix which we have installed in the previous chapter. We will create a blank site and then and add a page. To start with, click New and it will display the built-in templates. Templates are pre-built files and pages for different types of websites. To see all of the templates that are available by default, select the Template Gallery option. Select the Empty Site template and enter the Site Name. In this case, we have entered FirstWebPageDemo as the Site Name and then we have to click Next. It will install the required packages. Once the installation is finished, WebMatrix creates and opens the site as shown in the following screenshot. Create an ASP.NET Web Page Now to understand and become familiar with WebMatrix and ASP.NET Web Pages, let’s create a simple web page by clicking New in the Home tab. WebMatrix displays a list of file types as shown in the following screenshot. Select CSHTML, and in the Name box, enter FirstPage.cshtml and click Ok. Now you can see that WebMatrix has created the page and opens it in the editor. Let us first update the FirstPage.cshtml page as shown in the following program. @{ } <!DOCTYPE html> <html lang = “en”> <head> <meta charset = “utf-8″ /> <title>Welcome to ASP.NET Web Pages Tutorials</title> </head> <body> <h1>Hello World, ASP.NET Web Page</h1> <p>Hello World!</p> </body> </html> Now to test this web page, let’s select the arrow which is below the Run option on the Home tab and select Internet Explorer as shown in the following screenshot. Now you will see the following empty web page. Now let’s specify the following url − http://localhost:46023/firstpage in the browser and you will see the following output. Print Page Previous Next Advertisements ”;