Upload Files In RAZOR With jQuery Uploadify Plugin

16. March 2011 16:35

ASP.NET MVC Jquery 

A Few months back I wrote a post on how to use jQuery plugin Uploadify to upload single/multiple files without postback in ASP.NET. The program works similarly to simple file upload sites in its ease of use. Now a few days back I was working on a demo project which is on MVC 3 Razor and I use the same plugin without any problems. But the files that are being uploaded are uploaded to the root folder instead of the folder I specified to upload the files. After a lot of head scratching, I was unable to find the actual problem as why the file was not being uploaded to the folder of my choice. The answer was hidden in the normal file upload code that I saw in a forum posted by a user. So I gave it a try and it WORKED!! I was about to blog about the usage of uploadify plugin, but before that one of my blog reader asked me a question about uploading the files in Razor, though it was a bit different but this way it is pretty.

How do I do it?

Using the uploadify plugin in MVC 3 is the same as used with web forms, the only difference is that on the server-side we are going to use Controller and not a ASP.NET handler. Client side script is the same and there are only changes in script and folder parameter. Set the multi parameter to true if you wish to upload multiple files. 

<script type="text/javascript">
    $(window).load(
    function () {
        $("#fileuploader").fileUpload({
            'uploader': '/Scripts/uploader.swf',
            'cancelImg': '/Images/cancel.png',
            'buttonText': 'Select Image',
            'script': 'Home/Upload',
            'folder': '/uploads',
            'fileDesc': 'Image Files',
            'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
            'multi': true,
            'auto': true
        });
    }
);
</script>

The script tag specifies the method in the Home Controller which handles the file upload. The Upload method in the Home Controller:

public string Upload(HttpPostedFileBase fileData)
{
            var fileName = this.Server.MapPath("~/uploads/" + System.IO.Path.GetFileName(fileData.FileName));
            fileData.SaveAs(fileName);
            return "ok";
}

Now you can use the uploadify plugin with MVC 3 Razor and upload files in a more effective and efficient way and that too with no postback.

Download: FileUploader.zip (572.92 kb)

Currently rated 4.2 by 30 people

Using jQuery To Get Your Tweets

27. December 2010 16:10

API Jquery 

If you are a blogger and using Twitter, then you must want to show some of your latest tweets on your blog space. I do have a custom widget for my blog which can display 3 of my latest tweets and I can customize it show more of my tweets. But the widgets cannot be used in every scenario and this is why some people find it difficult to use the widget provided by Twitter to display their tweets. What if they want to show their last tweet on the top of the page inside a DIV? A friend of mine set up his new WordPress blog and want to have a DIV on the top of the page which displays his last post and that he can customize. By customize I mean that he can set the number of tweets he wants to display, can show his profile picture and get his last tweet. The script file contains only three methods at this moment. I will add some other functions later on.

How does this work?

It is just a javascript file and there is nothing new about it. What you need to do is to have a DIV or any HTML element or ASP.NET server control with id as 'tweet-div'. For this example I am using a DIV to show my tweets. I choose DIV because I can set it position to absolute and set on the image to show my latest tweet on an image I got from Iconsinder. It is a pretty twitter imageand there are other images also which you can use, but for non-commercial purpose only. First, take a look at the jQuery script I wrote to do all the stuff:

function GetLastTweet(UserName) {
    url = 'http://api.twitter.com/1/statuses/user_timeline/' + UserName + '.json?callback=?';
    $.getJSON(url, function (tweet) {
        $("#tweet-div").html(tweet[0].text);
    });
}

function GetTweets(UserName, NoOfTweets) {
    url = 'http://api.twitter.com/1/statuses/user_timeline/' + UserName + '.json?callback=?';
    $.getJSON(url, function (tweets) {
        for (var i = 0; i < NoOfTweets; i++) {
            $("#tweet-div").append(tweets[i].text + "<br/>");
        }
    });
}

function GetProfileImage(UserName) {
    url = 'http://api.twitter.com/1/statuses/user_timeline/' + UserName + '.json?callback=?';
    $.getJSON(url, function (image) {
        $("#ProfileImage").attr('src', image[0].user.profile_image_url);
    });
}

To communicate with the Twitter API, I am using JSON. Plan to go for XML only if you are using it on the server side code. As you can see it is pretty easy to work with JSON in jQuery. The methods:

  • GetLastTweet(UserName) will get the last tweet of any user. Pass the twitter user name as a parameter.
  • GetTweets(UserName, NoOfTweets) will get the specified number of tweets for the user. the first parameter will be the twitter user name and the second parameter will be the number of tweets you want to display.
  • GetProfileImage(UserName) will get the profle image of the user.

Note: Please change the element ID in the script file according to your element id on the page.

And just in case if you are feeling lazy to write the the HTML markup:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>@prashantmx on Twitter!</title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/Tweet.js" type="text/javascript"></script>
    <link href="style/style.css" rel="stylesheet" type="text/css" />
</head>
<body onload="GetLastTweet('prashantmx');">
<img src="images/1293447412_bird_sign.png" alt="twitterbird" />
<div id ="tweet-div">
</div>
</body>
</html>

I am using an image of twitter bird to show my last tweet. Check it out here. And here is what my last tweet looks like:

If you want to use the below image or other images like this then go to Iconfinder. There is a good collection of twitter birds images as shown below and choose which best suites your requirement.

P.S. I will be adding more functions to the script file at the later stage.

Demo: http://demo.midnightprogrammer.net/jquery/twitter/twitter.htm

Download: Twitter.zip (159.92 kb)

Currently rated 1.4 by 5 people

Autocomplete With jQuery and ASP.NET

19. December 2010 01:46

ASP.NET C# Jquery 

Building auto-complete feature with jQuery is easy and you can build this in no time. It's your wish if you want to use ADO.NET or EF (LINQ) to get this done, it works great for all. The sample application I build is using both ADO.NET and EF. So let's begin up getting files under one hood.

Use the below live links for jQuery auto-complete and CSS.

<link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.css" type="text/css" />
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>

You can also download these files and use them in your project, if you are planning to run your application offline. For this demonstration, I have downloaded the files. I am using both ADO.NET and LINQ to auto-complete with jQuery auto-complete pug-in.

Starting up with ADO.NET, as we were/are using this for so many years now and therefore there should be no problem for anyone using it. Simple page behind code to get the full list of countries in the world (I hope I have all of them) and seperate each country name with a '|' pipe symbol so I can split countries name and set it to the text box for auto-complete.

 public partial class _Default : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
        SqlCommand cmd;
        SqlDataReader dr;

        public string Listcountries;

        private string countryName()
        {

            StringBuilder sb = new StringBuilder();
            cmd = new SqlCommand("Select country_name from Country order by country_name", con);
            con.Open();
            dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                sb.Append(Convert.ToString(dr[0] + "|"));
            }

            return Convert.ToString(sb);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Listcountries = countryName();
        }
    }

Done with code behind and now only requires few lines of client script on the page to get the auto-complete running.

<script type="text/javascript">
        $(document).ready(function () {
            var cc = '<%=Listcountries%>'.split("|");
            $("#autoText").autocomplete(cc);
        });
</script>

The same can be done with LINQ but the jQuery script part will be the same.

public partial class AutocompleteLINQ : System.Web.UI.Page
    {
        DeveloperDBEntities db = new DeveloperDBEntities();
        public IQueryable countries;
        public string Listcountries;

        protected void Page_Load(object sender, EventArgs e)
        {
            countries = from c in db.Countries select c;
            foreach (Country cobj in countries)
            {
                Listcountries += cobj.Country_Name + "|";
            }
        }
    }

Just for your ease to use this project as it is, I have included the SQL scripts for the country table. Hope this helps you in building another great or a part of your application.

Downalod: JqueryAutoComplete.zip (210.73 kb)

Currently rated 3.3 by 6 people

Upload Multiple Files With jQuery "Uploadify"

12. September 2010 11:00

API ASP.NET Jquery 

I have found many web developers seeking for help to upload a file in AJAX style, I am not a web developer but among the list of people who used to search the web for some control, way or a workaround to do this. I found a .NET control to do this, but like all good controls....it wasn't free. But the control worth it.

But now we have an excellent open source plugin called Uploadify. I have been using it for sometime and thought I should now blog and spread a word about it. To implement in your ASP.NET project is simple. Download the latest version of Uploadify from its official site here.

Take a look at the downloaded files. Actually, I need NOT to explain it again to you because the download itself has a PDF file which makes it really simple to understand the working and usage of the plugin. If you need to take a look how this plug-in works, then the  best place to look at the demo page at the uploadify page here.

I also compiled a small apllication with ASP.NET to see it in action with ASP.NET

NOTE: The code below I have uploaded is not written by me, I have just compiled a bunch of files under one hood to get it working.

Download: JqueryUploadify.zip (229.05 kb)

Currently rated 4.0 by 2 people

Change Page Themes Dynamically Using JQuery Theme Roller

4. July 2010 12:21

Jquery 

If you are using JQuery controls like date picker, accordion, progress bar, slider, tabs, dialog etc. You can set the theme of your choice or you can also allow the user to set the theme of their choice. For those folks who don’t know about the JQuery Theme Roller, then take a look at official Jquery site demonstrating the Jquery Theme Roller. The best part is when you select the theme from the theme roller control all the JQuery controls on the page will automatically inherit the color scheme of the theme.

 To incorporate Theme Roller in your page, build a simple page and link some CSS and some JavaScript

<link type="text/css" rel="stylesheet" href="http://jqueryui.com/themes/base/ui.all.css" />
<link rel="stylesheet" 
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/base/jquery-ui.css" 
type="text/css" media="all" />
<link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" 
type="text/css" media="all" />
<script type="text/javascript" src="http://jqueryui.com/js/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" 
type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js" 
type="text/javascript"></script>

Now under the head section we will have the JQuery Theme Roller control.

    $(document).ready(function () {
        $('#ThemeRoller').themeswitcher();
    });

Notice the ThemeRoller id of the control passed in the JQuery code to initialize the Theme Roller/Switcher. Now in the Body tag of your page set a div with id as ThemeRoller or whatever the name you want to give, but make sure you use the same name as your control id.

<script type="text/javascript"
  src="http://jqueryui.com/themeroller/themeswitchertool/">
</script>
<div id="ThemeRoller"></div>

I have set the theme roller on the body of the page and therefore all the controls on the page will automatically change the theme accordingly set by the user using the theme roller on the page. You can also set a DIV or a form on your page instead of setting it for the complete page. Set some other controls on the page like date picker, progress bar, dialog etc. Html code for the controls.

Set some other controls on the page like date picker, progress bar, dialog etc.

<p>Date: <input id="datepicker" type="text" />
</p>
    
<div id="dialog" title="Basic dialog">
    <p>
    This is a Demo Dialog box using JQuery!!<br />
    Change theme to see this Dialog in different theme.
    </p>
</div>
    <div id="progressbar" style="width:200px;">

    </div>

Placing HTML code isn’t enough. You also need to set the JQuery code in the head section of the page to get the controls working. When you set all the JQuery code for the controls you body and head section of the page looks something like this.

Body section of the page:

<body style="font-size:62.5%;">
  
<script type="text/javascript"
  src="http://jqueryui.com/themeroller/themeswitchertool/">
</script>
<div id="ThemeRoller"></div>

<p>Date: <input id="datepicker" type="text" />
</p>
    
<div id="dialog" title="Basic dialog">
    <p>
    This is a Demo Dialog box using JQuery!!<br />
    Change theme to see this Dialog in different theme.
    </p>
</div>
    <div id="progressbar" style="width:200px;">

    </div>
</body>

Head section of the page:

<head>
<title>JQuery Theme Roller</title>
<link type="text/css" rel="stylesheet" href="http://jqueryui.com/themes/base/ui.all.css" />
<link rel="stylesheet" 

href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/base/jquery-ui.css" 

type="text/css" media="all" />
<link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" 

type="text/css" media="all" />
<script type="text/javascript" src="http://jqueryui.com/js/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" 

type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js" 

type="text/javascript"></script>


<script type="text/javascript">
//Set theme roller 
    $(document).ready(function () {
        $('#ThemeRoller').themeswitcher();
    });

//Show date time picker control
    $(function () {
        $("#datepicker").datepicker();
});

//Show Dialog
    $(function () {
        $("#dialog").dialog();
    });

//Progress Bar
    $(function () {
        $("#progressbar").progressbar({
            value: 50
        });
    });

</script>
</head>

Now try setting the theme of the page in one click using the Theme Roller. Check the live demo here

Currently rated 4.5 by 25 people