ASP.NET 4.5 Hosting BLOG

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

ASP.NET Hosting - ASPHostPortal.com :: New Ways To Organize Razor Views in ASP.NET Core

clock May 30, 2016 20:50 by author Armend

New Ways To Organize Razor Views in ASP.NET Core

Currently there are many ways to extend or to organize Razor views in ASP.NET Core. Let us start with the new more complex ways. If your are familiar with previous ASP.NET MVC Frameworks you’ll definitely know most. But not almost all of that “old” stuff is still possible in ASP.NET Core MVC. Some of the listed below is completely new in ASP.NET Core. With this post, we’re going to try to write down all options to organize MVC Views in ASP.NET Core.

 

How To Organize Razor Views in ASP.NET Core

1. ViewComponents

This is one of new way to organize Razor views in ASP.NET Core. Sometimes you need to have something like PartialView, but with some more logic behind. In the past there was a way to use ChildActions to render the results of controller actions into a view. In ASP.NET Core, there is a new way (which I already showed in this post about ViewCmponents) with ViewComponents. This are a kind of mini MVC inside MVC, which means they have an own Controller, with an own single action and a view. This ViewComponents are completely independent from your current view, but also can get values passed in from your view. To render a ViewComponent you need to call it like this:

@Component.Invoke("Top10Articles");

2.  TagHelper

This little helpers are extensions of your view, which are looking like real HTML tags. In ASP.NET Core, you should use this TagHelpers instead of the HtmlHelpers because they are more cleaner and easier to use. Another huge benefit is Dependency Injection, which can’t be used with the HtmlHelpers, because the static context of extension methods. TagHelpers are common classes where we can easily inject services via the constructor. A pretty simple example on how a TagHelper could look like:

[TargetElement("hi")]
public class HelloTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "p";
        output.Attributes.Add("id", context.UniqueId);
        output.PreContent.SetContent("Hello ");
        output.PostContent.SetContent(string.Format(", time is now: {0}", 
                DateTime.Now.ToString("HH:mm")));
    }
}

This guy defines a HTML Tag called “hi” and renders a p-tag and the contents and the current Time.
Usage:

<hi>armend</hi>

Result:
<p>Hello armend, time is now: 18:55</p>

ASP.NET Core MVC provides many built in TagHelpers to replace the most used HtmlHelpers. E. g. the ActionLink can now replaced with an Anchor TagHelper:

@Html.ActionLink(“About ��, “About”, “Home”)

The new TagHelper to create a link to an action looks like this:

<a asp-controller=”�� asp-action=”��>About me</a>

The result in both cases is a clean a-Tag with the URL to the about page:

<a href=”/Home/��>About me</a>

As you can see the TagHelpers feel more than HTML and they are easier to use and more readable inside the Views.

3. Dependency Injection

This is the biggest improvement to organize Razor views in ASP.NET Core. Yes, you are able to use DI in your View. Does this really make sense? Doesn’t it mess up my view and doesn’t it completely break with the MVC pattern? (Questions like this are currently asked on StackOverflow and reddit). We think, no. Sure, you need be careful and you should only use it, if it is really needed. This could be a valid scenario: If you create a form to edit a user profile, where the user can add its job position, the country where he lives, his city, and so on. We would prefer not to pass the job positions, the country and the cities from the action to the view. We would prefer only to pass the user profile itself and We only want to handle the user profile in the action. This is why it is pretty useful in this case to inject the services which gives me this look-up data. The action and the ViewModel keeps clean and easy to maintain.
Just register your specific service in the method ConfigureServices in the Startup.cs and use one line of code to inject it into your view:

@inject DiViews.Services.ICountryService CountryService;

Now you are able to use the ContryService in your View to fill a SelectBox with list of countries.

4. Global View Configuration

Last but not least, there is a separate razor file you can use to configure some things globally. Use the _ViewImports.cshtml to configure usings, dependency injections and many more which should be used in all Views.

Conclusion

There are many new ways to extend and organize Razor views in ASP.NET Core. But you are free to decide which feature you want to use to get your problems solved. While there are many programming languages out there for a web developer to choose from, one of the most successful programming language till this date is ASP.NET. It has matured over the years with the latest version, ASP.NET Core, having a number of new features and enhancements. You may already have heard that ASP.NET hosting is offered by several web hosting providers. However, choosing the best cheap ASP.NET hosting isn’t an easy task.

 



ASP.NET Hosting - ASPHostPortal.com :: How To Create a Help Desk Web Application using ASP.NET

clock May 24, 2016 20:04 by author Armend

Suppose you work for a small to midsize company that employs 50-100 workers. The Help Desk -- a subsidiary of the Information Services Division -- is in charge of trouble tickets regarding general PC issues such as email, viruses, network issues, etc. Initially, the Help Desk team stored this information in Excel spreadsheets, but as the company has grown, managing these spreadsheets has become tedious and time consuming.

The Help Desk has asked you to devise a more efficient solution that could be developed internally, saving the company money. As you start to think about it, the following requirements are apparent: fields for the submitter's first and last name, as well as their email address. You'll also need combo boxes for indicating ticket severity (low, medium, high), department, status (new, open, resolved), employee working on the issue, as well as an area for comments. Of all the solutions available, creating an internal help desk Web application with ASP.NET is relatively simple.

In the following article, we'll see how to implement these features in an ASP.NET help desk Web application using a database-driven approach,
Creating the JavaScript File
Because creating the JavaScript file is the easiest of the work left, we'll do this next. From the Solution Explorer, follow these steps:

Creating the Help Desk Class

Now that we have our data coming in, we need to be able to record a help desk ticket submission. We need to create an event handler in a class to handle it. Let's first create a help desk class by doing the following:

  •     Right click the project solution.
  •     Choose Add>New Item.
  •     In the Add New Item window, select Class.cs.
  •     In the name text field, type "HelpDesk" and then click Add.

Double click HelpDesk.cs from the Solution Explorer, which will show the empty class as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HelpDesk
{
    public class HelpDesk
    {
    }
}

We need to import three libraries as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace HelpDesk
{
    public class HelpDesk
    {
    }
}

The first library (System.Data) allows us to work with stored procedures in ADO.NET, the second (System.Configuration) allows us to reference a connection key from configuration file and the last (System.Data.SqlClient) one allows us to connect to SQL Server.

 

 



ASPHostPortal.com Announces DotNetNuke 8.0.2 Hosting Solution

clock May 18, 2016 00:10 by author Dan

ASPHostPortal.com was established with the goal to provide high quality hosting services for everyone. We believe that providing high quality services should come at an affordable price. For this reason we have provided exceptional plans, at the lowest prices, for the best services possible, on fastest nodes ever. Today, we offer DotNetNuke 8.0.2 hosting with cheap price and good service.

DotNetNuke is an expandable Web Application Platform. Third party applications and services can be deployed as DotNetNuke Modules. Modules are pieces of code that each present some functionality to the user, like a personnel contacts list, events calendar, or a list of announcements. Installing a module is a simple administrative task and it does not require programming. Once installed, third party modules are visually integrated with the rest of the site because they use the graphic styles of the current Skin.

Modules are completely integrated with the site security and internationalization settings. Modules can be easily added, edited, deleted, restored, moved around on a page, or transferred to other pages. DotNetNuke is fully localized. Built-in multi-language localization features allow administrators worldwide to easily use and adapt DotNetNuke software for their own use. Over 50 Language Packs are available through the DotNetNuke community.

ASPHostPortal.com provides Premium DotNetNuke 8.0.2 hosting plan on high performance servers and high-speed internet connection in the world. Every server is equipped with at least 2x Intel Xeon Quad-Core processors and massive amounts of memory. We are using SSD’s for storage, which provides much higher performance in terms of I/O and data transfer speed. The servers are connected to the network using multiple 1Gbps ports (bond network). To learn more about our DotNetNuke 8.0.2 Hosting, please visit http://asphostportal.com/DotNetNuke-8-0-2-Hosting

About ASPHostPortal.com:
ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: How to set up Output Caching in ASP.NET

clock May 17, 2016 19:52 by author Armend

How to set up Output Caching in ASP.NET

Hi today we are talking about Output Caching in ASP.NET , so i hope you will enjoy and get something from it .

What is Output Caching ?

Output caching has enabled developers to store the generated output of pages, controls, and HTTP responses in memory. On subsequent Web requests, ASP.NET can serve content more quickly by retrieving the generated output from memory instead of regenerating the output from scratch.

Limitation :

Generated content always has to be stored in memory, and on servers that are experiencing heavy traffic, the memory consumed by output caching can compete with memory demands from other portions of a Web application.

Role in ASP.NET  5 :

ASP.NET 5 adds an extensibility point to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism to persist HTML content. This makes it possible to create custom output-cache providers for diverse persistence mechanisms, which can include local or remote disks, cloud storage, and distributed cache engines.

You create a custom output-cache provider as a class that derives from the new System.Web.Caching.OutputCacheProvider type. You can then configure the provider in the Web.config file by using the new providers subsection of the outputCache element, as shown in the following example:

&lt;caching&gt;
&lt;outputCache defaultProvider="AspNetInternalProvider"&gt;
&lt;providers&gt;
&lt;add name="DiskCache"
type="Test.OutputCacheEx.DiskOutputCacheProvider, DiskCacheProvider"/&gt;
&lt;/providers&gt;
&lt;/outputCache&gt;
&lt;/caching&gt;


By default in ASP.NET 4, all HTTP responses, rendered pages, and controls use the in-memory output cache.You can change the default output-cache provider used for a Web application by specifying a different provider name for defaultProvider.

&lt;%@ OutputCache Duration="60" VaryByParam="None" providerName="DiskCache" %&gt;

 

Specifying a different output cache provider for an HTTP request requires a little more work. Instead of declaratively specifying the provider, you override the new GetOuputCacheProviderName method in the Global.asax file to programmatically specify which provider to use for a specific request. The following example shows how to do this.

public override string GetOutputCacheProviderName(HttpContext context)
{
if (context.Request.Path.EndsWith("Advanced.aspx"))
return "DiskCache";
else
return base.GetOutputCacheProviderName(context);
}

With the addition of output-cache provider extensibility to ASP.NET 4, you can now pursue more aggressive and more intelligent output-caching strategies for your Web sites. For example, it is now possible to cache the “Top 10” pages of a site in memory, while caching pages that get lower traffic on disk.



ASP.NET Hosting - ASPHostPortal.com :: 5 Tips to Check Before Choose FREE ASP.NET Hosting Provider

clock May 11, 2016 21:22 by author Armend

5 Tips to Check Before Choose FREE ASP.NET Hosting Provider

Hosting Account Setup

After you place an order of web hosting you should get hosting account instantly or it should not be delayed more than 12 hours and the another thing there is very little effort required in creating a new hosting service so it should be free. But you can see so many web hosts charge you money as a setup fee that's just silly.

 

Web Space and Bandwidth

As you might aware web resources are always limited like there is fixed amount and quantity of hard drive, ram, cpu in the web server and looking for unlimited package is just a impractical idea. Ftp or upload complete personal website data to your hosting space you require only 20mb web space to 100mb web space maximum so why looking for unlimited features? Most of cheap unlimited hosting providers have data server outage issue repeatedly so selecting unlimited web hosting in cheap price can cease your expensive website data.

Technical support for customers

There is already big giant in web hosting, cheap hosting and free hosting industry which have very professional sales team for the clients and they use all mode of support system for the new clients via phone, live chat, ticket, email, voip but when it is the time to raise a technical issue concerned to your hosting account that time there would be the problem and so many of your hosting issue wont be resolved by their technical customer support. So besides searching for cheap hosting price you should also look for skilled and good customer support system for tech.

Control Panel and Hosting Features

Various control panel for web disk are available and many are worst and few are excellent and easy to manage. Mostly client had issue with windows panel like plex and cpanel is very familiar. Many hosts provide multiple domains hosting in a single hosting account which is cheap and easy to handle but when you require is to transfer or migrate your hosting account from old hosting to new hosting in that time probably there would be the problem. In your hosting you should look for database, ftp, php, phpMyadmin, MySql, application installer, virus scanner, email accounts, subdomain, folder locker, url forwarding, backup, seo tool etc at free of cost without upgrades.

Always Read the Terms and Conditions

You are agreed with terms and conditions before you start hosting with them so make sure you read all the terms, refund policy, money laundering policy, resource abuse policy, privacy policy etc.

 



ASPHostPortal.com Announces ASP.NET Core 1.0 Hosting Solution

clock April 26, 2016 23:37 by author Dan

ASPHostPortal.com is a well-known Windows hosting company and even one of the most famous, though it is one of the oldest Windows hosting companies. Our packages have gone through major changes recently, and all of them goes for the goodness of every customers. Today, we launch ASP.NET Core 1.0 hosting with interested hosting packages.

3 months ago, the ASP.NET team announced during the weekly ASP.NET Community Standup was decided to rename ASP.NET 5 to ASP.NET Core 1.0. The whole “ASP.NET 5 MVC 6 Web API 2 sub-component version scheme was confusing. They’ve been working towards “One ASP.NET” now for years and they’re there. ASP.NET Core is versioned as 1.0 as it’s a near complete rewrite of ASP.NET with many new features and capabilities. It’s clearly a different product than ASP.NET 4.6.

.NET Core is a modular, streamlined subset of the .NET Framework and CLR. It is fully open-source and provides a common set of libraries that can be targeted across numerous platforms. Its factored approach allows applications to take dependencies only on those portions of the CoreFX that they use, and the smaller runtime is ideal for deployment to both small devices (though it doesn’t yet support some) as well as cloud-optimized environments that need to be able to run many small applications side-by-side. Support for targeting .NET Core is built into the ASP.NET 5 project templates that ship with Visual Studio 2015.

ASPHostPortal.com offers ASP.NET Core 1.0 Hosting with an interested hosting plan. We support this new technology with affordable price, a lot of ASP.NET features, 99.99% uptime guarantee, 24/7 support, and 30 days money back guarantee. We strive to make sure that all customers have the finest web-hosting experience as possible. To learn more about our ASP.NET Core 1.0 Hosting, please visit http://asphostportal.com/ASPNET-Core-1-0-Hosting

About ASPHostPortal.com:

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: How to Add the Store Locator in ASP.NET MVC Application

clock April 22, 2016 23:13 by author Dan

Recently, a reader wrote in and asked what steps would be necessary to include a “Directions” link with each marker in the map so that, when clicked, the user would see the driving directions from the address they entered and the store of interest. I decided to update the ASP.NET MVC application to include this new feature request. Now, the results page shows a “Directions” link in both the grid of nearby stores and in the info window that pops up when you click a map marker. Clicking the “Directions” link opens a new browser window and loads Google Maps, showing the directions from the user-entered address to the selected store’s address.

To show the driving directions I send the user to the following URL: http://maps.google.com/maps?f=d&source=s_d&saddr=startingAddress&daddr=destinationAddress.

When the user is sent to the store locator page, the user-entered address (a/k/a, the starting address) is passed through the querystring via a field named Address, so we already know the starting address. But how do we get our hands on the destination address? Recall that view is passed a model that is a collection of NearbyStoreLocation objects; the NearbyStoreLocation class has properties like Address (the street address), City, Region, PostalCode, and so forth. We can build up the address by concatenating these various address parts.

Rather than requiring the view to build up the address, I added a new read-only property to the NearbyStoreLocation class named FormattedAddress, which returns an address Google Maps can parse by piecing together the address-related properties into a string.

public string FormattedAddress
{
get
{
var addrPieces = new List<string>(5);
if (!string.IsNullOrEmpty(this.Address))
addrPieces.Add(this.Address);
if (!string.IsNullOrEmpty(this.City))
addrPieces.Add(this.City);
if (!string.IsNullOrEmpty(this.Region))
addrPieces.Add(this.Region);
if (!string.IsNullOrEmpty(this.CountryCode))
addrPieces.Add(this.CountryCode);
if (!string.IsNullOrEmpty(this.PostalCode))
addrPieces.Add(this.PostalCode);
return string.Join(", ", addrPieces.ToArray());
}
}

In the view, the link to the directions can be build like so:

<a target="_blank" href="http://maps.google.com/maps?f=d&source=s_d&saddr=<%=Server.UrlEncode(Request.QueryString["Address"]) %>&daddr=<%=Server.UrlEncode(store.FormattedAddress) %>">Directions</a>

And that’s it! Adding the Directions link to the info popup window is a tad more involved because the quotation marks must be escaped using \”. Happy Programming!

Best ASP.NET 4.6 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET hosting -ASPHostPortal.com :: Top 10 Tips You Shall Know on Choosing ASP.NET Hosting

clock April 22, 2016 20:34 by author Armend

Top 10 Tips You Shall Know on Choosing ASP.NET Hosting

Being devoted into ASP.NET development and ASP.NET website hosting for a couple of years, we know the secrets hidden in the ASP.NET hosting advertisement and how difficult to find a trusted and cost effective ASP.NET hosting provider. Thus, we would like to show you the top 10 tips on choosing ASP.NET hosting providers before starting with our topic.

  1. MS SQL Server database edition and limitation. The latest version of MSSQL 2012 are preferred.
  2. .NET Framework versions. Does it support the version used for your website?
  3. ASP.NET MVC versions. Does it support the version used for your website if you’re using ASP.NET MVC technology?
  4. Does it provide the dedicated application pool so that you won’t be affected by your neighbors?
  5. How long the IIS is set to recycle your website – usually 30 minutes at least is required.
  6. What’s the maximum dedicated memory allowed for the ASP.NET websites?
  7. The hosting provider needs to have the rich experiences and knowledge of how to ensure the high-quality ASP.NET hosting. Besides, it is great that they have got plenty of positive feedbacks from real customers and have been trusted and recommended by a lot of authorities, communities and hosting review sites.
  8. The ASP.NET hosting needs to ensure a high level of hosting reliability with at least 99.9% uptime. Note that this can be achieved with the utilization of cutting-edge data centers, solid server machines and no overselling practice. In addition, some confident web hosts even claim to give you some compensations if they fail to meet their promised uptime track record.
  9. The hosting speed is also pretty essential. After all, your readers can be frustrating if they find it takes a long time for accessing your website. In this case, you need to figure out that whether your web host can ensure the peak performance with no more than 3 seconds for page loading and 400 ms for the server response.
  10. The web host needs to ensure the all-time-rounded technical support to assist you 24 hours a day and 7 days a week. Also, their support staffs need to have the rich knowledge about ASP.NET hosting and related applications.

General Knowledge about ASP.NET

ASP.NET is the server-side online application framework coming with the open source nature. It is designed with the purpose of web development and dynamic webpages production mainly. In addition, developed by Microsoft, ASP.NET has been used by a lot of programmers for the creation of complicated websites, online applications and add-on services.
In fact, ASP.NET has been released since January 2002, which is the successor to the Active Server Pages technology of Microsoft. As it is built based on the Common Language Runtime, developers and programmers can write the ASP.NET code with the help of .NET language.

 



ASP.NET Hosting - ASPHostPortal.com :: Why Server Speed is Important for Increasing Revenues

clock April 12, 2016 19:31 by author Armend

Why Server Speed is Important for Increasing Revenues

If your website loads slower and takes long to respond you are literally killing your sales and revenue with your own hands. Today, the key to more sales and conversion is the combination of effective content with faster loading speed of your website. The speed of your website is the time taken from a web page to become visible on the screen after it has been requested by the browser.

The latest surveys showed that loading speed of websites has a great impact on the traffic trends. The speed of the website has a great importance, a slow website could easily frustrate your potential customers forever.

 

A slow website reflects low revenue

Often the slower websites have high bounce rates with poor sales. A number of studies have proven that the average visitors will leave your website if it does not become accessible in 3 to 6 seconds. Slower website is not only a reason to decrease your sales but the frustrated visitors are likely to develop a negative perception about your business.

Does Speed of the website can increase the revenue?

Did you know the world popular brand Shopzilla generated 12% more revenue by simply improving the website speed from 6 seconds to 1.2 seconds?

It is no more a secret that google records the web page speed to determine the ranking of the website along with other organic ranking factors. You can check the speed of your pages by inspecting the Google webmaster tools.

According to latest calculated formula you can improve 2% of conversion rate by simply speeding up the website by every single second. Shopzilla , Amazon, Yahoo and Mozilla experienced a great boost in business by speeding up the loading speed of the web pages to less than 3 seconds.

Shopzilla increased 12% revenue along with 25% increased page views
Yahoo got a 9% increase in the traffic
Mozilla got 60 million more downloads by simply improving the web page speed to 2.2 seconds faster

How fast is fast enough for a web page?

The ideal loading time of a website is under 3 seconds. If your website becomes visible in 5 seconds it seems to be good. If it is under 10 seconds it is considered to be as fair. However if your website exceeds 10 seconds you are losing the ranking and conversion. The slower your website is the less sales you will have.
There are several performance metric tools available to report the performance of your website speed along with web page improvement suggestions. You can optimize the structure of your code to get faster responses. However you certainly need hosting power to execute your application quickly to load your website faster.

Choose fast dedicated server for faster website

The speed of a website mainly depends on the architecture of your web pages, databases and the speed of hosting servers. Going with the right kind of web hosting could make or break your website ranking. Shared hosting and dedicated hosting are two major types of hosting service available online. Shared service has a low price with low resources available. Shared hosting is designed to deliver small websites with low traffic. Dedicated hosting is an expensive option with more power and performance.
Businesses are adapting dedicated server technology for more speed and power. All sorts of critical online businesses can reap the benefit of fast powerful dedicated hosting. Server speed may be the issue if your website resides on one of the cheapest shared or vps hosting service holding hundreds of websites. Shared hosting can not offer you the true speed and reliability as its resources are shared by many websites hosted on the same computer. If you have a business website, mobile application or a professional service website, fast dedicated hosting can make a difference in search engine ranking.

Below are some great advantages of dedicated hosting for faster website.

  • Your website will load faster
    • The dedicated server is a powerful machine designed and configured to execute the processes in fastest manners. Dedicated hosting has more reliable infrastructure, bandwidth and resources as compared to any other type of hosting service. Dedicated hosting enables your website to execute faster and tremendously increase the loading speed of your website.
  • Your website will be more secure
    • Another great advantage of dedicated hosting is the safety of your business data. Usually hackers break into the websites by locating a poorly coded website hosted nearby on shared hosting environment. If you have hammer tested your code for common vulnerabilities you can easily lock down your server for better security and data safety.
  • Your website will handle more traffic
    • If you have a popular website or advertising your business you may experience sudden traffic spikes at certain times. Dedicated server enables you to tackle high load without going down. If you have optimized your code and server you are in a better position to handle your website traffic faster and smoothly.


ASP.NET Hosting - ASPHostPortal.com :: How to Call ASP.NET Page Methods using your own AJAX

clock March 15, 2016 20:04 by author Armend

ASP.NET has grown very rich day by day. Recently Microsoft has introduced JQuery as a primary javascript development tool for client end application. Even though there is a number of flexibility in ASP.NET AJAX applications, many developers do seek place to actually call a page using normal AJAX based application. In this post I will cover how you can invoke an ASP.NET page method directly from your own AJAX library.

What are page methods?

A Page method is a method that is written directly in a page. It is generally called when the actual page is posted back and some event is raised from the client. The pageMethod is called directly from ASP.NET engine.

What is a WebMethod?

A WebMethod is a special method attribute that exposes a method directly as XML service. To implement PageMethod we first need to annotate our method as WebMethod.
Steps to Create the application :
1. Start a new ASP.NET Project.
2. Add JQuery to your page. I have added a special JQuery plugin myself which stringify a JSON object. The post looks like below :

(function ($) {
$.extend({
toJson: function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj &amp;&amp; obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" &amp;&amp; v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
}
});
// extend plugin scope
$.fn.extend({
toJson: $.toJson.construct
});
})(jQuery);

The code actually extends JQuery to add a method called toJSON to its prototype.

3. Add the server side method to the Default.aspx page. For simplicity we actually return the message that is received from the client side with some formatting.

[WebMethod]
public static string DisplayTime(string message)
{
// Do something
return string.Format("Hello ! Your message : {0} at {1}", message, DateTime.Now.ToShortTimeString());
}

Remember : You should make this method static, and probably should return only serializable object.

4. Add the following Html which actually puts one TextBox which takes a message and a Button to call server.

&lt;asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"&gt;
&lt;h2&gt;
Welcome to ASP.NET!
&lt;/h2&gt;
&lt;p&gt;
Write Your message Here : &lt;input type="text" id="txtMessage" /&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;input type="button" onclick="javascript:callServer()" value="Call Server" /&gt;
&lt;/p&gt;
&lt;/asp:Content&gt;
Once you add this html to your default.aspx page, add some javascript to the page. We add the JQuery and our JSONStringify code to it.
&lt;script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="Scripts/JSONStringify.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
function callServer() {
var objdata = {
"message" : $("#txtMessage").val()
};
$.ajax({
type: "POST",
url: "Default.aspx/DisplayTime",
data: $.toJson(objdata),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (xhr, ajaxOptions) {
alert(xhr.status);
}
});
}
&lt;/script&gt;

The above code actually invokes a normal AJAX call to the page. You can use your own library of AJAX rather than JQuery to do the same. On success, it returns the serializable object to msg.d.



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