Showing posts with label ASP.NET. Show all posts
Showing posts with label ASP.NET. Show all posts
Thursday, February 7, 2013

Redirection with ASP.Net friendly URLs

In this post we are going to see how we can use Response.Redirect(Redirecttion) in asp.net friendly URLs. Before some day I have written a post about ASP.NET Friendly URLs – Cleaner, SEO friendly URLs. On that post one reader ‘Ramesh’ asked me that how we can do redirection with ASP.Net friendly URLs. So this post is in reply to Him.

How to redirect a page to ASP.Net friendly URLs:

Actually!! there is nothing to learn. It’s very easy You can directly use the ‘Response.Redirect’ with the ASP.Net friendly URLs. The NuGet Package itself takes care of all the things. You just need to write the route name as a parameter in ‘Response.Redirect’ and you are done!!

Uh!! don’t believe me!!. Let’s take a sample example. I am going to use by default template with ASP.NET Friendly URLs.  So for this example I have created a ASP.Net button in Default template AboutUs.aspx page. Once the click of that button we are going to use ‘Response.Redirect’ for redirection and redirect this page to Contact Page. Following is a html code for that button.
Share:
Monday, February 4, 2013

ASP.NET Friendly URLs – Cleaner, SEO friendly URLs

Search Engine optimization is one of the key factor for your site. If you spend millions of dollars on making your website looks good and bug free then also its possible that you will not get attention of search engine because of your URLs.  For example you’re having shopping cart created in asp.net and you have not optimized your URL then it will look like following.

www.foo.com ?Product.aspx?Category=1& Page=1

If you search engine read this URL then search engine will not know much about this URLs. Even normal people  who does not know querystring menaing(?Category=watch&Page=1) will not understand it. But If you have URL like following.

www.foo.com/prduct/category/watch/page/1

It’s easy to read and search engine and normal people will know that you are loading products that belongs to category watch and this is a first page.
Share:
Sunday, February 3, 2013

What’s new in ASP.NET and Web Tools 2012.2 Release Candidate

Recently before some time, Scott Gu announced ASP.NET and Web Tools 2012.2 Release Candidate. I have downloaded it and used it for a while and I have found following new things.

ASP.NET Enhancements:

  • New facebook asp.net mvc template is  there. Creating facebook application with asp.net mvc become very easy. In just a few step you can easily create facebook application and get data of users and friends of facebook.
  • Real Time Signal R support is there. You can easily create chat kind of applications with it. You can also take advantage of new web socket in .NET 4.5.
  • New updates with ASP.NET WEB Api now supports OData, Integrated tracing and automatically generating help document for your api
  • ASP.NET Friendly URLs: This feature makes developers life very easy with creating SEO friendly and cleaner looking URLs with out .aspx extension. The Friendly URLs feature also makes it easier for developers to add mobile support to their applications with support for mobile .ASPX pages and  supporting switching between desktop and mobile views.  It can be used with existing ASP.NET v4.0 applications
  • Enhancement to Web publishing
  • All new single page application template with knock out JavaScript library and restful UI.
Share:
Saturday, February 2, 2013

How to hide title bar in jQuery UI modal dialog?

jQuery UI is a great open source set of user controls and it’s very easy to use. Recently one of my friend asked question that how we can hide title bar in jQuery UI Dialog? so this post is a reply to him. Let’s create a simple html and use jQuery Ui modal dialog. Following is a code for that.

Here in the above code you can see I have create a hello world pop up with asp.net jQuery CDN.
<html>
<head>
    <title>Hello World  Popup</title>
    <link type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.0/themes/smoothness/jquery-ui.css"
        rel="stylesheet" />
    <script language="javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
    <script language="javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.0/jquery-ui.min.js"></script>
    <script type="text/javascript">
        function Show() {

            $("#dialog:ui-dialog").dialog("destroy");

            $("#dialog-modal").dialog({
                height: 300,
                width: 200,
                modal: true
            });
        }
    </script>
</head>
<body>
    <div id="dialog-modal" title="Hello Word" style="display: none">
        Hello World Juqry UI popup
    </div>
    <input type="button" onclick="javascript: Show()" value="click me" />

</body>

</html>


Share:

How to create overload methods in WCF service with C#

Before some days I have posted an blog about How to create overloaded web methods in asp.net web service? In this post I am going to explain how we can create overload methods in WCF(Windows Communication Foundation) service with C# language.

So let’s consider same Hello world example which we have used web service overload method. Let’s create two methods HelloWorld one is with name and another is without parameter. For WCF service we have to first create interface following is a code for that.
Share:
Friday, February 1, 2013

Getting started with Twitter Bootstrap and ASP.Net MVC


Update: Now with ASP.NET MVC5 you don't need to install twitter bootstrap nuget package now its by default available with default template.

In this blog I am going explain how we are  going integrate Twitter Bootstrap library with ASP.Net MVC.

What is Twitter bootstrap:

Twitter Bootstrap is open source library created by Twitter. As per twitter it’s Sleek, intuitive, and powerful front-end framework for faster and easier web development. It’s full featured framework for creating web sites. It includes CSS framework, JavaScript, JavaScript plug-ins,typography, Html scaffolding. There are lots of themes also available that are available so you can use that right away.

Integrating Twitter bootstrap with ASP.Net MVC:

Earlier we have to manually integrate Twitter bootstrap into the ASP.NET MVC like here. But now We have Twitter.Bootstrap.MVC4 Nuget packages that saves lots of time to adding bootstrap to MVC4 template. It’s very easily combines bootstrap into ASP.NET MVC application thanks  to it’s authors Matt Hinze and Eric Hexter.

As per Eric Hexter It’s provide following features.
  • JS and CSS bundling/minification of Twitter Bootstrap files the MVC4 way
  • Incorporate a jQuery validation fix to work with the bootstrap javascript
  • Razor Layout templates using Twitter Bootstrap markup.
  • Menus using Navigation Routes, including submenus and hiding menus by context(logged in vs anonymous)
  • Runtime Scaffolding – default Index, Edit and Detail views.. You provide thePOCOs and we will render the CRUDviews.
  • Post Redirect Getsupport using the Bootstrap Alert styles.
  • A Sample to show how to use all of this stuff
Share:
Wednesday, January 30, 2013

How to create overloaded web methods in asp.net web service?

Recently some of colleagues were discussing about how to create overload methods in web service. We can’t directly create overloaded method web methods for web service. So I thought It would be great idea to write a blog post about it.

Function Overloading:


Function overloading is one of most known concepts of Object Oriented Programming. It’s a technique to implement polymorphism in code. Like in other programming language in c# you can also create multiple functions with same name and different argument. In function overloading function call will be resolved by ‘Best Match Technique’.

Problem: You cannot directly overload method in web service:


To understand this let’s create a simple web service with two HelloWorld Methods one with parameter and one without parameter both will return a string. Following is a code for that.
Share:
Sunday, December 2, 2012

Dynamic URL of asp.net web service with web reference

It’s been a while I am writing this. But never late.. So I am writing this. Before some time one of friend asked about the URL of web service when we add reference. So I am writing this. Some of you may find this very basic but still many of people does not know this that’s why I am writing this.

In today’s world we have so many servers like development, preproduction and production etc. and for all the server location or URL of web service will be different.But with asp.net when you add a web reference to your web application it’s create a web reference settings in web.config where you can change this path. So it’s very easy to just change that path and you don’t have to add web reference again.
Share:
Tuesday, July 17, 2012

Model binding with ASP.NET 4.5 and Visual Studio 2012

Note:I have written a whole series of Visual Studio 2012 features and this post will also be part of same series. You can get the whole list of blogs/articles from the Visual studio 2012 feature series posts there. Following is a link for that.Visual Studio 2012 feature series
In earlier version of the asp.net we have to bind controls with data source control like SQL Data source, Entity Data Source, Linq Data Source if we want to bind our server controls declaratively. Some developers prefer to write whole data access logic and then bind the data source with databind method. Model binding is something similar to asp.net mvc binding.

Model Binding in ASP.NET 4.5 and Visual Studio 2012:


With ASP.NET 4.5 and Visual studio 2012 we have a new method of binding data called ‘ Model binding’. It’s a code focus approach of data binding. Now all the controls will have ItemType property which will implement strongly type binding. The server controls will then call appropriate methods at the proper time in page life cycle and bind the data.

So what we are waiting for ? let’s take one example. First we need to create a model. For the this I have created a model class called ‘Customer’. Following is code for that.
Share:
Saturday, July 7, 2012

Dividing web.config into multiple files in asp.net

When you are having different people working on one project remotely you will get some problem with web.config, as everybody was having different version of web.config. So at that time once you check in your web.config with your latest changes the other people have to get latest that web.config and made some specific changes as per their local environment. Most of people who have worked things from remotely has faced that problem. I think most common example would be connection string and app settings changes.

For this kind of situation this will be a best solution. We can divide particular section of web.config into the multiple files. For example we could have separate ConnectionStrings.config file for connection strings and AppSettings.config file for app settings file.

Most of people does not know that there is attribute called ‘configSource’ where we can  define the path of external config file and it will load that section from that external file. Just like below.

<configuration>
 <appSettings configSource="AppSettings.config"/>
 <connectionStrings configSource="ConnectionStrings.config"/>
</configuration>

And you could have your ConnectionStrings.config file like following.
Share:
Monday, July 2, 2012

Multiple file upload with asp.net 4.5 and Visual Studio 2012

Note: This post will be part of Visual Studio 2012 feature series.
In earlier version of ASP.NET there is no way to upload multiple files at same time. We need to use third party control or we need to create custom control for that. But with asp.net 4.5 now its possible to upload multiple file with file upload control.

With ASP.NET 4.5 version Microsoft has enhanced file upload control to support HTML5 multiple attribute. There is a property called ‘AllowedMultiple’ to support that attribute and with that you can easily upload the file. So what we are waiting for!! It’s time to create one example.
On the default.aspx file I have written following.

<asp:FileUpload ID="multipleFile" runat="server" AllowMultiple="true" />
<asp:Button ID="uploadFile" runat="server" Text="Upload files" onclick="uploadFile_Click"/>

Here you can see that I have given file upload control id as multipleFile and I have set AllowMultiple file to true. I have also taken one button for uploading file.For this example I am going to upload file in images folder. As you can see I have also attached event handler for button’s click event. So it’s time to write server side code for this. Following code is for the server side.

protected void uploadFile_Click(object sender, EventArgs e)
{
    if (multipleFile.HasFiles)
    {
        foreach(HttpPostedFile uploadedFile in multipleFile.PostedFiles)
        {
            uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Images/"),uploadedFile.FileName));
            Response.Write("File uploaded successfully");
        }
    }
}

Share:
Wednesday, June 27, 2012

Interview questions about ASP.NET Web services.

I have seen there are lots of myth’s about asp.net web services in fresher level asp.net developers. So I decided to write a blog post about asp.net web services interview questions. Because I think this is the best way to reach fresher asp.net developers. Followings are few questions about asp.net web services.

1) What is asp.net web services?
Ans: Web services are used to support http requests that formatted using xml,http and SOAP syntax. They interact with through standards xml messages through Soap. They are used to support interoperability. It has .asmx extension and .NET framework contains http handlers for web services to support http requested
directly.


2) What kind of data can be returned web services web methods?
Ans: It supports all the primitive data types and custom data types that can be encoded and serialized by xml. You can find more information about that from the following link.
http://msdn.microsoft.com/en-us/library/bb552900.aspx

3) Is web services are only written in asp.net?
Ans: No, It can be written by Java and PHP languages also.

Share:

Bundling in visual studio 2012 for web optimization

Note: I have been writing a series of posts about Visual Studio 2012 features. This series describes what are the new features in the Visual Studio 2012. This post will also be part of Visual Studio 2012 feature series.
As we know now days web applications or site are providing more and more features and due to that we have include lots of JavaScript and CSS files in our web application.So once we load site then we will have all the JavaScript  js files and CSS files loaded in the browsers and If you have lots of JavaScript files then its consumes lots of time when browser request them.
Following images show the same situation over there.

Bundling feature in Visual Studio 2012 - Visual Studio 2012 feature series

Here you can see total 25 files loaded into the system and it's almost more than 1MB of total size. As we need to have our web application of site very responsive and need to have high performance application/site, this will be a performance bottleneck to our site. In situation like this, the bundling feature of Visual Studio 2012 and ASP.NET 4.5 comes very handy. With the help of this feature we do optimization there and we can increase performance of our application.
Share:
Friday, May 25, 2012

ASP.NET Web API Basics

We have seen that now web is really becoming cross plate form and you can see your services or API can be exposed to any client. Till now one of big challenges is to choose platform for this kind of service. There are so many options available like web services, WCF services,Generic Handlers, directly writing responses on aspx page etc. There are plenty of options available and each one has their own pros and cons.  But now we have one simpler answer for that is ASP.NET Web API.

What is Web API?

ASP.NET Web API is a framework for building web API on the top of .NET framework. It’s a framework for building and consuming web services that can be use at broad range of clients like browsers,tablets phones etc. You can expose JSON or XML whatever you want to use.

Why to use Web API?

Think about a situation where a jQuery script that is making a ajax request and we need some thing who can expose data from the server to the client at that time WEB API can be very handy you can expose server data in XML or JSON form and you can make that call with simple http request. No lengthy code required to call WEB API.
Share:
Friday, April 20, 2012

File Upload in ASP.NET MVC3

If you are a web developer you often need to upload file on the web server or database. In today’s post I am going explain how we can upload file in ASP.NET MVC 3 with razor syntax.

So, first thing we need to create a view that will contain the file upload control. I am going to use an existing asp.net mvc template for this demo. So I have just modified the default Index view like following.
Share:
Saturday, January 7, 2012

Difference between generic handler and http handler- ASP.NET

Generic handler:

As per MSDN Generic Handler is a default handler which will have @webhandler directive and has .ashx extension this generic handler is not having UI but it provides response when ever any request made to this handler.

HTTP Handler:

HTTP Handler is a process which runs and continue to server request and give response based on the request handling code. This handler does not have UI and need to configured in the web.config against extensions. One of the great example of Http Handler is page handler of ASP.NET which serves .aspx pages request.

Difference between generic handler and http handler:

Following is a main differences between http handler and generic handler.
  1. Generic handler has a handler which can be accessed by url with .ashx extension while http handler is required to be configured in web.config against extension in web.config.It does not have any extension
  2. Typical example of generic handler are creating thumbnails of images and for http handler page handler which serves .aspx extension request and give response.
Hope you liked it.Stay tuned for more..Till then happy programming.

Shout it

kick it on DotNetKicks.com
Share:

ASP.NET Page Methods with Parameters

In earlier post I have written how we can use page methods to call server-side from the java script. In this post I am going to explain How we can pass parameters to page methods with java script.
So let’s take a simple example to see how we can pass parameters to the page methods. I am going to create a page method Hello World which takes name as parameter and return a string to greet user from that page method below is code for that.

using System;
using System.Web.Services;

namespace PageMethods
{
 public partial class Test : System.Web.UI.Page
 {
    [WebMethod]
    public static string HelloWorld(string name)
    {
        return string.Format("Hi {0}",name);
    }
 }
}

As you can see in following page method it’s returning string with greetings. So now our server-side code is completed. Now it’s time to write HTML and java script code for this. Following is code for java script.

<script type="text/javascript">
 function GreetingsFromServer() {
     var name = 'Jalpesh';
     PageMethods.HelloWorld(name,OnSuccess, OnError);
     return false;
 }
 function OnSuccess(response) {
     alert(response);
 }
 function OnError(error) {
     alert(error);
 }
</script>

As you can see in above code I have created a function called ‘GreetingsFromServer’ which called page method helloworld with passing name parameter. Other two functions are handlers for the page methods Onsucess will be called if page method is called successfully without error other wise it will call onError method and alert error message.

Now we are done with java script so its time to write HTML code. So let’s write a HTML code for this page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="PageMethods.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Page Method with parameter demo</title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
     <asp:ScriptManager runat="server" EnablePageMethods="true" EnablePartialRendering="true">
     </asp:ScriptManager>

     <asp:button ID="btnHelloWorld" runat="server" Text="Greet User" OnClientClick="return GreetingsFromServer();"/>
 </div>
 </form>
</body>
</html>

As you can see from above code I have enabled page methods true with script manager and then I have called JavaScript function “GreetingsFromServer” on button client click. So it’s now time to run this code in browser. Following is output as expected.

PageMethodWithParameter

That’s it. It’s very easy hope you liked it..Stay tuned for more…Happy programming

Shout it

kick it on DotNetKicks.com
Share:
Saturday, December 24, 2011

Page methods in asp.net

Now days people are looking for richer and fluid user experience and to create that kind of application Ajax is required. There are several options available to call server-side function from JavaScript with ASP.NET Ajax and if you are using asp.net 2.0 or higher version of Microsoft.NET Framework then page methods are one of best options available to you.

Page methods are available there from asp.net 2.0. If works just like a normal web service. You can direct call that page methods directly from the JavaScript.

Let’s take a real world example. I will call java script on button client click event and then from that we call server-side function from the page methods. So let’s create a project called Pagemethods via File->New Project like following

Page methods in ASP.NET

After that I have created a page called test.aspx and now I am creating page method called GetCurrentDate like following.

using System;
using System.Web.Services;

namespace PageMethods
{
   public partial class Test : System.Web.UI.Page
   {
      [WebMethod]
      public static string GetCurrentDate()
      {
          return DateTime.Now.ToShortDateString();
      }
   }
}

As you can see in above there is  a web method called GetCurrentDate which is just returning short date in string format. Here you will notice that I have putted WebMehod attribute for that method this is a perquisite for page methods to make available in client side.

Now let’s write code for HTML and JavaScript and following is a HTML code for that.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="PageMethods.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Page Method demo</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
       <asp:ScriptManager runat="server" EnablePageMethods="true" EnablePartialRendering="true">
       </asp:ScriptManager>

       <asp:button ID="btnGetDate" runat="server" Text="Get date from server" OnClientClick="return GetDateFromServer();"/>
   </div>
   </form>
</body>
</html>

As you can see in above code I have taken an ASP.NET button which call client side function GetDateFromServer which call page methods and get server date. Following is a javascript code for that.

<script type="text/javascript">
   function GetDateFromServer() {
       PageMethods.GetCurrentDate(OnSuccess, OnError);
       return false;
   }
   function OnSuccess(response) {
       alert(response);
   }
   function OnError(error) {
       alert(error);
   }
</script>

As you can see in GetdateFromServer methods I have called our page method Get Current date and you can see PageMethods object in JavaScript has all the methods which are available from server-side. I have passed two event handler for success and error. If any error occurred then it will alert that error and on successful response from server it will alert a current date.

So it’s now time to run that in browser.So once you pass F5 then once you click ‘Get date from server’ the output is like following as expected.

PageMethodOutput

That’s it as you see it’s very easy.Hope you like it. Stay tuned for more.Till then happy programming..

Shout it

kick it on DotNetKicks.com
Share:
Friday, December 23, 2011

Async file upload with jquery and ASP.NET

Recently before some I was in search of good asynchronous file upload control which can upload file without post back and I have don’t have to write much custom logic about this. So after searching it on internet I have found lots of options but some of the options were not working with ASP.NET and some of work options are not possible regarding context to my application just like AsyncFileUpload from Ajax toolkit.As in my application we were having old version of Ajax toolkit and if we change it than other controls stopped working. So after doing further search on internet I have found a great Juqery plugin which can easily be integrated with my application and I don’t have to write much coding to do same.

So I have download that plug from the following link. This plug in created by yvind Saltvik

After downloading the plugin and going through it documentation I have found that I need to write a page or generic handler which can directly upload the file on the server. So I have decided to write a generic handler for that as generic handler is best suited with this kind of situation and we don’t have to bother about response generated by it.

So let’s create example and In this example I will show how we can create async file upload without writing so much code with the help of this plugin. So I have create project called JuqeryFileUpload and our need for this example to create a generic handler. So let’s create a generic handler. You can create a new generic handler via right project-> Add –>New item->Generic handler just like following.

GenericHandlerForJqueryFileUploadwithASPNET

I have created generic handler called AjaxFileuploader and following is simple code for that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace JuqeryFileUPload
{
   /// <summary>
   /// Summary description for AjaxFileUploader
   /// </summary>
   public class AjaxFileUploader : IHttpHandler
   {

       public void ProcessRequest(HttpContext context)
       {
           if (context.Request.Files.Count > 0)
           {
               string path = context.Server.MapPath("~/Temp");
               if (!Directory.Exists(path))
                   Directory.CreateDirectory(path);

               var file = context.Request.Files[0];

               string fileName;

               if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
               {
                   string[] files = file.FileName.Split(new char[] { '\\' });
                   fileName = files[files.Length - 1];
               }
               else
               {
                   fileName = file.FileName;
               }
               string strFileName=fileName ;
               fileName = Path.Combine(path, fileName);
               file.SaveAs(fileName);

              
               string msg = "{";
               msg += string.Format("error:'{0}',\n", string.Empty);
               msg += string.Format("msg:'{0}'\n", strFileName);
               msg += "}";
               context.Response.Write(msg); 

              
           }
       }

       public bool IsReusable
       {
           get
           {
               return true;
           }
       }
   }
}


As you can see in above code.I have written a simple code to upload a file from received from file upload plugin into the temp directory on the server and if this directory is not there on the server then it will also get created by the this generic handler.At the end of the of execution I am returning the simple response which is required by plugin itself. Here in message part I am passing the name of file uploaded and in error message you can pass error if anything occurred for the time being I have not used right now.

As like all jQuery plugin this plugin also does need jQuery file and there is another .js file given for plugin called ajaxfileupload.js. So I have created a test.aspx to test jQuery file and written following html for that .

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="JuqeryFileUPload.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title></title>
   <script type="text/javascript" src="jquery.js"></script>
   <script type="text/javascript" src="ajaxfileupload.js"></script>
</head>
<body>
   <form id="form1" runat="server">
   <div>
         <input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input">
         <button id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>
         <img id="loading" src="loading.gif" style="display:none;">
   </div>
   </form>
</body>
</html>

As you can see in above code there its very simple. I have included the jQuery and ajafileupload.js given by the file upload give and there are three elements that I have used one if plain file input control you can also use the asp.net file upload control and but here I don’t need it so I have user file upload control. There is button there called which is calling a JavaScript function called “ajaxFileUpload” and here we will write a code upload that. There is an image called loading which just an animated gif which will display during the async call of generic handler. Following is code ajaxFileUpload function.

<script type="text/javascript">
   function ajaxFileUpload() {
       $("#loading")
   .ajaxStart(function () {
       $(this).show();
   })
   .ajaxComplete(function () {
       $(this).hide();
   });

   $.ajaxFileUpload
   (
       {
           url: 'AjaxFileUploader.ashx',
           secureuri: false,
           fileElementId: 'fileToUpload',
           dataType: 'json',
           data: { name: 'logan', id: 'id' },
           success: function (data, status) {
               if (typeof (data.error) != 'undefined') {
                   if (data.error != '') {
                       alert(data.error);
                   } else {
                       alert(data.msg);
                   }
               }
           },
           error: function (data, status, e) {
               alert(e);
           }
       }
   )

       return false;

   }
</script>

As you can see in above code I have putted our generic handler url which will upload the file on server as url parameter. There is also parameter called secureURI is required to be true if you are uploading file through the secure channel and as a third parameter we have to pass a file upload control id which I have already passed and in fourth parameter we have to passed busy indicator which I have also passed. Once we passed all the parameter then it will call a method for plugin and will return response in terms of message and error. So There is two handler function written for that.

That’s it. Our async file upload is ready. As you can easily integrate it and also it working fine in all the browser. Hope you like it. Stay tuned for more. Till then happy programming..
Share:
Thursday, December 22, 2011

Redirection in URL Routing

In one of the my earlier post I have written How easily we do URL rewriting in ASP.NET Web forms. In this post I am going to explain redirection in URL Routing.

In web application it’s a common scenario that we are redirecting our page to the one from the another and those who are familiar with the ASP.NET Web Forms will also know how we can use  Response.Redirect() to redirect from one page to another page.  In ASP.NET 4.0 Web Forms they have given same kind of Method to redirect to a particular route. The method is Response.RedirectToRoute(). With the help of this method you can redirect to any particular route. Response.RedirectToRoute() has different overload method you can find more information about it from following link.

http://msdn.microsoft.com/en-us/library/dd992853.aspx

Real Example of Response.RedirectToRoute


Iam going to use same example which I have used in my earlier post. We are going to add a new page called Index.aspx. After adding the page. I am going to add following code to global.asax to map index.aspx to launch by default.

using System;
using System.Web.Routing;

namespace UrlRewriting
{
public class Global : System.Web.HttpApplication
{

protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routeCollection)
{
routeCollection.MapPageRoute("RouteForCustomer", "Customer/{Id}", "~/Customer.aspx");
routeCollection.MapPageRoute("DefaultRoute", string.Empty, "~/Index.aspx");
}

}
}

As you can see in above I have added a default route to map index.aspx. Following is HTML code for index.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="UrlRewriting.Index" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>This is my home page</h1>
<asp:button ID="btnGoToCustomer" runat="server"  Text="Goto first Customer" 
onclick="btnGoToCustomer_Click"/>
</div>
</form>
</body>
</html>

As you can see in above code I have created a ASP.NET Button called for redirection and on click of that button I have written following code for that.

protected void btnGoToCustomer_Click(object sender, EventArgs e)
{
Response.RedirectToRoute("RouteForCustomer",new {Id=1});
}

As you can see in above code I have redirect it to ‘Customer' route and I am passing Id as “1” so it will load details of customer whose id is 1.

Let’s run this example via pressing F5. So it will directly load index.aspx page as homepage like following.

HomePageForURLRedirection- ASP.NET 4.0 URL Routing and revwriting

Now once you click on button It will redirect to custom page and will display customer information.

CustomerDetailsPage

So that’s it. You can see it’s very easy redirect pages with URL routing. Hope you like it. Stay tuned for more.Till then Happy programming..

Shout it
kick it on DotNetKicks.com
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews