Handling Text Changed Event In ASP.NET MVC 3 With JQuery

16. July 2011 13:00

ASP.NET MVC Jquery 

In my quest of learning MVC I came across many problems and here is one of them. I was trying to fire an event whenever a text changed event occurred. I am using JQuery to handle the text changed event but eventually the text changed event doesn't seems to be working in MVC as it is working for a text box changed event in web forms. The solution I found seems to be working fine for me as I don't want to fire an event on every key press.

To get started fire Visual Studio and create a new MVC 3 application with RAZOR view engine. I have build a simple contact manager application which allows the user to create a new contact, edit and delete existing contacts. While creating a new contact, what I want is when the user enters the e-mail address of the contact I want to make an AJAX call, which then call the method in the controller and return the HtmlString which will then show the Gravatar on the webpage.

Here is the default view of the index view. I will ask the user to enter some very basic information like name, address, email and phone.

Now, when the user enters the email address of the contact and press TAB key to move to another field or just click somewhere else on the page, the focus on the text field will be changed and the controller function then returns HtmlString to show the Gravatar image.

Here is the markup of the Create View (Create.cshtml):

@model TextChangedMVC.Models.Contacts
@{
    ViewBag.Title = "Create";
}
<h2>
    Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Contacts</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            <div id="Gravatar">
            </div>
            @Html.ValidationMessageFor(model => model.Email)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Phone)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Phone)
            @Html.ValidationMessageFor(model => model.Phone)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Check the highlighted code in the above markup where I have a DIV called Gravatar. This is where I will display the Gravatar of the person. Remember, when the user enters the email address we need to make sure that the Gravatar of the person displays without being an obstruction to the user, so an AJAX request to the controller will help in achieving this.

Below is the Jquery which will call the controller method called Avatar which accepts email as a parameter of string type.

<script type="text/javascript">
    $('#Email').change(function () {
        $('#Gravatar').html('');
        var selection = $('#Email').val();
        if (selection.length > 0) {
            $.post("/Home/Avatar", { email: selection },
        function (data) {
            $('#Gravatar').html(data)
        })
        }
    });
</script>

The above script is simple and here I am calling the controller's Avatar method which returns an HtmlString. At line 6, we are making a request and calling the controller's method. At line 8, the data (which is a HTML) returned will be set on the DIV called Gravatar (the placeholder for the Gravatar image).

The controller method Avatar is as follows:

public HtmlString Avatar(string email)
{
      return Gravatar.GetHtml(email, defaultImage: "http://midnightprogrammer.net/pics/default.gif");
}

Gravatar is a method is a part of the Microsoft Web Helpers. You can use web helpers by downloading it via NuGet. Check it out here if you miss my blog post on how to use Microsoft Web Helpers in MVC.

Related Post:

Currently rated 3.4 by 9 people

Bin Deploy ASP.NET MVC 3 Application With SQL CE 4.0 & Entity Framework

4. July 2011 14:26

.NET Framework ASP.NET MVC Visual Studio 

A few days back Phil Haack wrote a blog post on how to bin deploy ASP.NET MVC 3 application on the web server where ASP.NET MVC 3 is not installed. Like many users I am also on shared hosting and therefore I do not have full control over IIS or the remote machine so I can install or update ASP.NET MVC 3, SQL Server CE 4.0 and other development related stuff. Phil did an excellent post but that works only if you are deploying application with SQL Server as a database. If you are planning to deploy your application with SQL CE as your application backend then here are the steps you need to perform.

I assume that you have your ASP.NET MVC 3 application ready to be deployed with SQL CE 4.0 and EF 4.1. But make sure you have add assembly and for SQL CE 4.0 using NuGet. I recommend you to use NuGet here because it will add all the necessary configurations in Web.config file and also add the correct references to your project. If you have MVC 3 tools update installed then there is no need to add the references for SQL CE 4.0 and for EF 4.1, the default MVC 3 template will do it for you. But there are still some changes to be done in Web.config file.
 
To deploy your application with SQL CE 4.0 you need to make below changes to the web.config file:
 
Comment or delete everything inside the connectionStrings tag. The connection string by default is pointing to your default SQL Server instance and as we are going to deploy our application with SQL CE 4.0 we need to change the value under connectionStrings tag like the one below.
<add name="ContactEntities" connectionString="Data Source=|DataDirectory|DB.sdf" providerName="System.Data.SqlServerCe.4.0" />
Next is to add DbProviderFactories under System.Data tag. If you run the application on your local development server then it will run without any problems, but if you deploy the web application to the hosting web server where SQL CE 4.0 is not installed then you will get the below error.
 
 To avoid this error you need to manually add the DbProviderFactories in the Web.config file. Below in the markup you need to add to your web.config file.
<system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SqlServerCe.4.0" />
      <add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
    </DbProviderFactories>
</system.data>
The best way to do this and to avoid any unnecessary error is to use NuGet. If you use NuGet to deploy SQL CE 4.0 then it will add all necessary configurations to the web.config file, add the correct dependent assembly to the project.
 
Copy all the dependencies to the BIN folder

The question here is how the one knows what are the dependencies and where to find them all so that they can be deployed with the application? To perform this step you should have Visual Studio 2010 Service Pack 1 (VS 2010 SP1) installed on your machine. After installing VS 2010 SP1 there will be an option called Add Deployable Dependencies added when the user right-click the project icon in the solution explorer. When you click this option a dialog box appears which allows you to select the dependencies required for the project.

If you have read Phil's post by now, you might know the difference of all the above options. Here, as we are deploying SQL CE 4.0 database we will also check SQL Server Compact also. Click OK button to add all the required dependencies. As soon as you click OK button you will notice that a new folder named _bin_deployableAssemblies gets added to the solution explorer.

 

After adding all the dependencies you then need to build you web application which then copies all the dependencies to the project's or web application's bin folder. While deploying the application we will place each file with similar directory structure in the BIN folder on the hosting web server where ASP.NET MVC 3, SQL CE 4.0 and EF 4.1 is not installed. Just in case if you are wondering on how to deploy EF 4.1, then there is no other thing to be done to deploy EF 4.1, a DLL named EntityFramework inside the bin folder will do the work for us.

Note: I have made no changes to the directory structure while placing files at the remote hosting server.

Currently rated 5.0 by 1 person

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

Working With Microsoft Web Helpers In MVC 3 Razor View

6. March 2011 10:58

API ASP.NET MVC Microsoft 

Building applications with ASP.NET MVC 3 and that too with RAZOR is easy. I believe most of the programmers out there found MVC 3 with RAZOR view engine found it easy. The best things I found in the new RAZOR view engine is the code is pretty much tidy no traditional code behinds and moreover you can work with the server-side code with the start of the @ symbol.
What is a Helper Class?
I am not going to copy and paste the definition from somewhere but I want to write my own thoughts on the helper class. Maybe this is not the best definition but this is how I would like to describe the Helper Class.
A class that minimize the effort incurred in the design, implementation of functionality on your application is called a helper class.
One of the best things that Microsoft incorporated in the framework is the use of the helper classes. Although this is not a new concept, previously also all the programmers are working on their own to create helper classes for the work they are doing to minimize the effort and time spend in writing the same lines of code again and again. Microsoft Web Helpers provides some of the best helper classes that can be used in almost every web application.
How to get Microsoft Web Helpers
To use Microsoft Web Helpers in your project use the below NuGet command:
If you are using Web Matrix then you can start using the helper class right away, but if you have created the application from Visual Studio then you still need the Web Matrix reference in you project. You can add the Web Matrix reference from C:\Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies. Once installed, you can now use it for majority of the complex tasks with ease and in less time. Some of the major use of this helper class is listed below:
Using Web Helpers
Gravatar: To show the gravatar on your web page use the Gravatar class Gethtml() and pass e-mail address as a parameter. If the e-mail id provided, has no Gravatar then the default Garavatar image will be displayed. To get the Gravatar with default Gravatar image:
@Gravatar.GetHtml("prashant@midnightrogrammer.net")
 
You can also have your own default image to replace the default Gravatar image. To show your own default image use the defaultImage: attribute
@Gravatar.GetHtml("prashant@midnightrogrammer.net", defaultImage: "http://midnightprogrammer.net/pics/default.gif")
Twitter: Twitter helper class can be used to show your tweets using the Profile method. This will display the same widget that you can get for youself from the Twitter website. Moreover you can also change the apperance of the widget. To display your tweets you can use your twitter profile name as a parameter in the Profile method.
@Twitter.Profile("prashantmx")
 
You can also search Twitter and display all the reactions. If I have to search about Windows Phone 7 then I will use the keyword #WP7.
@Twitter.Search("#wp7")
 
For Twitter follow button:
@TwitterGoodies.FollowButton("prashantmx")
Tweet Button: The tweet button will help you to tweet your website or blog content. But this time we will use the TwitterGoodies class TweetButton
@TwitterGoodies.TweetButton(TwitterGoodies.DataCount.Horizontal, "This is RAZOR Tweet", "http://midnightprogrammer.net", TwitterGoodies.Languages.English,"prashantmx")
 
You can set the align of tweet counts either vertically or horizontally or none. I have set it to horizontal.
Google / Yahoo Analytics: Insert tracking code in your website directly
@Analytics.GetGoogleHtml("UA-9087")
Same can be done for Yahoo. Just use GetYahooHtml instead of GetGoogleHtml
Facebook: Facebook integration is now much easier. To get the like button use:
@Facebook.LikeButton("http://midnightprogrammer.net")
To show the latest activity feed use the ActivityFeed method. I am going to see the latest activity from Microsoft
@Facebook.ActivityFeed("http://www.microsoft.com")
 
Microsoft Bing Search: If you want to have a search then the best option is to use Microsoft Bing (Because It's Not Google). There are two Bing search boxes that you can use, but the most popular is the Bing Advanced Search Box. Below are the two ways to use the Bing Search box
Normal Search Box
@{
    Bing.SiteTitle = "Midnight Programmer";
    Bing.SiteUrl = "http://midnightprogrammer.net";
}

@Bing.SearchBox()
 
Advanced Search Box
The same code will be used to show the advanced search box, just use the AdvancedSearchBox method instead of SearchBox as done previously
@{
    Bing.SiteTitle = "Midnight Programmer";
    Bing.SiteUrl = "http://midnightprogrammer.net";
}

@Bing.AdvancedSearchBox()
The main advantage of using the advanced search box for Bing is that it will let you search the whole website/blog without taking you to the Bing site and display the search content in the small container with two tabs showing the search result from the website/blog and the other one from the web.
Note: Bing team at Microsoft announced that they will be shutting down siteowner service on April 4th. This will prevent you to use the AdvancedSearchBox feature of Bing on your website/blog or web applications. Here is the quote from Bing's official blog:
As of April 4th, 2011 we will discontinue support for the bing.com/siteowner functionality. If you continue to leverage the feature after this date (April 4th, 2011), users who attempt to query in the search box will be redirected to a 404 page. This means that you will need to move to the Bing API in order to continue to receive web or site search results from us. We have decided to take this step for two reasons.
First, the tool has not been getting a lot of use and while we have some very loyal customers on it, we believe we can provide you better alternatives in the future as we free up resources.
Second, the functionality available through bing.com/siteowner can be replicated with the Bing search API and so it feels a bit redundant.
As has become customary, we will give you a window to migrate off and ask us any questions you may have about this change. We will also provide reminders as we get closer to April 4th. Thank you so much for your support.
 
So this is it. These are some of the helper classes in action that I have described in this post. There are lot of others and I hope that there would be other helper classes would be added in the later releases of Microsoft helper classes for web. You can read more here on web helpers from the below official Mirosoft resources.

Download: DBMatrix.zip (1.13 mb)

Currently rated 5.0 by 7 people

RAZOR: View Engine In ASP.NET MVC 3

6. September 2010 16:26

ASP.NET MVC Visual Studio 

A new view engine is introduced in ASP.NET MVC 3 called RAZOR. You can download Preview 1 from Microsoft's download center and get it running on your machine to check the new features in MVC 3. Just in case if you are thinking that installing MVC 3 will mess your current MVC 2 installation....No, it won't. I came across a Webcamp video where Phil Haack with James Senior demonstrate this view engine. My this post is also based on the same talk.

So when you install MVC 3 Preview 1 on your machine, jump start by creating a new project in Visual Studio 2010. You will not be able to use this view engine with .NETFX 3.5 (SP1).

Now when you select new project and under Web templates you will now see ASP.NET MVC 3 application twice. The one template with (ASPX) is using normal web forms as your view engine and the other one with (Razor) is the new view engine. This is only for preview 1, these options will not be present in the final release of the MVC 3, instead you will have an oprion to select the view engine for your application later, I am not very sure how, but it will be more likely the way you select tests.

Time to check the Solution Explore. No .aspx files only .cshtml

The drawback in Preview 1 is that there is no syntax highlighting and no intellisense. Now that would have made you think "OMG! how am I going to write the code now!?". But Razor is easy and more over it too light-weight, more then I thought before I used it. Check out Index.cshtml, the markup code looks like this.

Time to take a look at Home Controller. Take a look at the Index() action method, the syntax is bit different with the one we have used previously.

 public ActionResult Index()
{      
       ViewModel.Message = "Welcome to ASP.NET MVC!";
       return View();
}

The line ViewModel.Message = "Welcome to ASP.NET MVC!"; is equivalent to:

public ActionResult Index()
{      
       ViewData["Message"] = "Welcome to ASP.NET MVC!";
       return View();
}


The ViewModel basically is of type dynamic which means that its operations will be resolved at runtime. Hover your cursor over ViewModel and Message to know about it.

If you need to show some addtional information related your current project you can set it too with ease. In the Index method you can add antoher line like this which says something about your project:

NOTE: As ViewModel is of Dynamic type, so when you press dot (.) after writing ViewModel don't expect that something will come up and as said before all expressions will be resolved at runtime.

public ActionResult Index()
{
      ViewModel.Message = "Welcome to ASP.NET MVC!";
      ViewModel.AboutApp = "This is a sample ASP.NET MVC 3 Preview 1 application!";
      return View();
}

To show this message on the Index view you will just call it by prefixing it with '@' symbol. To show the value on the page you simply write below line and prefix it with @ symbol(If you say this is simple, I would rather prefer to say it effortless).

@View.Message 
@View.AboutApp

Moving further, add a new class called Contacts (or what ever name you like) with 3 peoperties.

public class Contacts
{
    public string Name{ get; set; }
    public int Age{ get; set; }
    public string Email { get; set; }
}

Moving back to the HomeController add the below lines of code to the Index action method.

var ctc = new Contacts[] {
          new Contacts{Name="Prashant", Age = 23},
          new Contacts{Name="Arvind", Age = 24},
          new Contacts{Name="Max", Age = 23}
};

The view should not be empty this time. And therefore your Index action method return the Contacts we have just created.

public ActionResult Index()
{
ViewModel.Message = "Welcome to ASP.NET MVC!";
ViewModel.AboutApp = "This is a sample ASP.NET MVC 3 Preview 1 application!";             
var ctc = new Contacts[] {
          new Contacts{Name="Prashant", Age = 23},
          new Contacts{Name="Arvind", Age = 24},
          new Contacts{Name="Max", Age = 23}
          return View(ctc);
};
}

This time also Razor makes it simple to view the the data you returned from the controller. In the Index.cshtml you can do it pretty simply and you will still have a pretty looking markup of the view page. Create a list of contacts you have just created. As they are in a set of array, we can then enumerate the array with a foreach loop and show it on the page.

<ul>
@foreach (var c in Model){
<li> My name is @c.Name and I am @c.Age years old. </li>
}</ul>

You can easily get the data in a jiffy without writing a lot of markup. No problem in concatenating the data, the @ symbol and MVC compiler is pretty intelligent and does this for us. So what if we want to add e-mail addresses also. How this view engine will handle this ambiguity? Well let see. Just add an e-mail property to the array of contacts.

var ctc = new Contacts[] {
          new Contacts{Name = "Prashant", Age = 23, Email = "prashant@midnightprogrammer.net"
}

And on the view page the line will be something like this

<ul>
@foreach (var c in Model){
<li> My name is @c.Name and I am @c.Age years old. You can email me at @c.Email.</li>
}</ul>

Hit F5 and see it by yourself. There are lot of features described by Scott Guthrie and Phil Haack on their blog. Well I can go on writing and writing about Razor, so I think I should take a pause now and you can go to below links for more deep information about Razor view engine and to know what's new in the upcoming release of ASP.NET MVC 3.

Recommend Reading:

 No Rating