ASP.NET MVC Ajax.BeginForm Sample Code
I must admit enjoying ASP.NET MVC. Ajax is a must for all modern and respectable websites so I ended up using it over and over again. This little set of code snippet happened so often that I decided to write it down somewhere.
First, you will need to have an HTML element like for example a div that will contain a partial view:
<div id="mydiv"> <% Html.RenderPartial("MyPartialView", Model); %> </div>
This div is going to be updated by the Ajax-executed code. Second, the partial view will contain the Ajax.BeginForm() code needs to look like this:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyModel>" %> <% using (Ajax.BeginForm("AjaxActionName", "MyActionName", new AjaxOptions{ UpdateTargetId = "mydiv" })) { %> <input id="input1" type="text" /> <input id="input2" type="text" /> <input id="dosomething" type="submit" value="save" /> <span>The Answer is: <%= Html.Encode(Model.Count()) %></span> <% } %>
Take note that input1 and input2 are provided by the user and the result of the website is shown in the span. Finally, there should be a controller like the following:
[AcceptVerbs(HttpVerbs.Post)] public PartialViewResult MyActionName(string input1, string input2) { return PartialView("MyPartialView", DataHandling(input1, input2)); }
When the user clicks on ‘dosomething’ button, an Ajax call to ‘MyActionName’ action is made. The action handles the user inputs and updates ‘mydiv’ with the a new instance of ‘MyPartialView’. Only this time, ‘MyModel’ object passed to the partial view is the result of the website handling ‘input1′ and ‘input2′ from the user.
Linux vs Windows Web Hosting: Top Five Reasons That Could Change Your Mind
So you wrote and tested your new web application using PHP-MySQL and you’re wondering about Linux vs Windows web hosting. If you are like me, you don’t want to get involved with web server administration and especially not with server up-time. You want to concentrate on the business side, which made you consider choosing a web hosting service where you’ll have everything you need to get your website up and running for less than 10$/month. If this is your case, this article is to help you in the decision of a Linux vs Windows web hosting service.
Before I go any further, I would like to warn readers that are used to my critiques of Windows OS that when it comes to the server market, I am much more friendly to Windows. The main reason for this apparent confusion is that I mainly criticize Windows because of the perverse effects of its domination of the desktop market. This is less true in the server market where balance exist between 3 main players: Unix, Linux and Windows.
Linux vs Windows web hosting is not really an issue if you are a strictly PHP-MySQL developer and that after 10 years of web development, it never occurred to you to use an ASP.NET-based module. You’ll never need ASP.NET or SQL Server to run your application, so why bother? I would like to point a few reasons that are related to my own experience:
- There’s not a big difference in price: most Linux vs Windows web hosting difference in price is around 1$/month. If you need a dedicated server, price differences are in the same proportions. However, this price difference is only a fraction of your development or maintenance costs. Even if your website is not making money, you’re time is worth a lot more than you might think. See it this way: if you spend 20 hours a week developing and maintaining your website that is not making money, you are losing 20 times 50$/hour equals 1000$/week not working as a freelance consultant. If you do spend this time on your website, it is because you think it is worth the investment of 1000$/week. So why try to save 12$/year? Of course, this is if you live in North America and Europe where 1$/month doesn’t make a big difference in your pocket.
- You’re not loosing anything with Windows: most Windows web hosts will include PHP-MySQL. FastCGI on IIS 7 will host PHP with no problems. For that extra dollar, you’ll also be compatible with ASP.NET and SQL Server. If you are going to host many websites, then this option is going to be very attractive, especially if you might have to deploy solutions that are developed in ASP.NET (ex: Kigg, DotNetNuke).
- ASP.NET is gaining market share: C# is gaining popularity amongst developers. Therefore, chances that the next hot module is developed in .NET increases with time. Let’s say you found this great addition to your website and that it is written in ASP.NET. Does your Linux web host support mono project? If not, you’re not going to be able to use that addition.
- Windows gained some market share: same thing goes here for windows platform. Until 2006, Apache was de facto choice of web server. But Windows 2003 and IIS were stable enough to convince enough webmasters to own more that one fifth of the market today. This means that a lot of innovative will show up on the Windows platform exclusively and that you might not want to miss them.
- Don’t go crazy over security: The strongest argument against Windows is security. Don’t forget that this is true for the desktop market where 90% of PCs run on Windows, making it the dream target for hackers. However, when it comes to web servers, it is the website’s popularity that comes in play. What it means that unless you are not having huge traffic, security is not really an issue. When you’ll get traffic, you’ll need to invest in security and that is going to cost you as much in both platforms because the real cost again is in human resources as opposed to the platform.
In this article, I have explored the case of Linux vs Windows web hosting for those who want to outsource web server administration. This will be an issue in the first few months where traffic is not important. But even after, when you’ll have a clientele, the platform is not an issue. The big reason is that human resource costs are the main operations cost for your business. Since Windows will give more compatibility and interoperability, it becomes a wiser decision to go for this platform, as a lot of webmasters are going for it.
Using Partial Views with ASP.NET MVC AJAX
One thing I struggled to figure-out when I moved to ASP.NET MVC was how to work with its AJAX model. I was used to work with UpdatePanels and the Ajax Community Tookit that are event-based WebForms controls. Especially for someone who was used to deal with the rich set of controls from Ajax Community Toolkit, it was hard to have nothing more than basically two Ajax function: Ajax.ActionLink() and Ajax.BeginForm(). Well believe it or not, ASP.NET MVC Ajax model ended-up working quite well for me, as the secret lies in Partial Views. That makes a lot of sense since Ajax is all about updating part of a web page. The only hard thing was that I had to get used to ASP.NET MVC’s paradigm shift from event-based WebForms.
So this is typically the way I work. First, I create a partial view and add the Ajax code in it:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.MyModel>" %> <%= Html.Encode(Model.ValueToDisplay) %> <%= Ajax.ActionLink("ActionText", "ActionName", new { id = Model.id, controller = "ControllerID" }, new AjaxOptions { UpdateTargetId = Model.id.ToString() })%>
Now, the trick is that this PartialView is placed in a HTML div that’s id is equal to Model.id, which should make the page look like this:
<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<MyNamespace.MyModel>" %> <div id="<%= Model.id %>"> <% Html.RenderPartial("ThePartialViewAbove", Model); %> </div>
The Controller Action should look like this:
public PartialViewResult Edit(string id) { MyModel cmt; // Put data query code here for cmt return PartialView("ThePartialViewAbove", cmt); }
Now, what happens is that when the Edit action is called (i.e. when the Ajax.ActionLink is clicked), the Model.id div is refreshed with the content of ThePartialViewAbove, which is based on updated data in Edit action. Wow, that’s easy. I love it.
Switching From WebForms to ASP.NET MVC: Is it Worth it?
There are a lot of good stuff about the new ASP.NET MVC framework, but a question remains for developers who have invested heavily in developing applications and skills on WebForms: is it worth switching to ASP.NET MVC? For those who are interested in technical differences between both platforms, you can refer to the this article. What I will concentrate on here is productivity gain. At least for me, there was a real gain, although I had to deal with the little hassles of this new framework.And lets not forget, there are much more rich controls available for WebForms than ASP.NET MVC.
Well, to tell you the truth, relearning ASP.NET MVC wasn’t hard at all. It took me a couple of minutes to figure out how to create a Controller (right-click on project’s ‘Controller’ folder and click on ‘Create Controller…’ menu option) and to associate a View to an Action (simply call View() function and right-click on it and then select ‘Add View…’ menu option).
What I enjoyed more than anything was LINQ integration with Views. That’s partly because I really hated dealing with Data Controls like the Repeater or ListView. I mean they are great for plugging DataSources to them, but when it comes to customizing, they are nightmare. With LINQ and their IEnumerable objects, you have real power in your hands when it comes to have fast custom things on the View. What I really enjoy is code like the following:
<% foreach(SomeClass obj in Model) { %> <% = Html.Encode(Model.SomeAttribute) %> <% } %>
My feeling is that this kind of stuff gives great freedom to the developer which can lead to real time-saving also.
Aslo, ASP.NET MVC is much closer to HTML, so some of those send back/post back issues are not there anymore. I guess this is something else ASP.NET MVC developers don’t have to deal with.
Integration of ASP.NET Forms Authentication with Twitter OAuth
In a previous article, I proposed a custom Forms Authentication for Facebook connect. The need for such a measure come from the fact that both Forms Authentication and Facebook Connect use cookies as means of authenticating users. Things are quite different on Twitter OAuth because it does not send any cookie to the browser: everything happens with HTTP requests. As a result, a Twitter Application developed in ASP.NET can use Forms Authentication without being in conflict with Twitter OAuth’s own cookie system.
There is something else to consider in Twitter OAuth, and that is the secret key that is associated with a Twitter account’s lifetime. Actually, the secret key never expires, which means that the Twitter App could keep a user connect as long as needed.
So the trick is that once the user has authorized your application to perform status update, you make a call to ‘http://twitter.com/account/verify_credentials.xml‘ to retrieve the users screen name. All you have to do, is call
1 | FormsAuthentication.SetAuthCookie("<em>Screen_Name</em>", true); |
to set the cookie on the users browser. If you want the user to be logged on for eternity (well you can’t have a user connect for more that a year), set the timeout value to whatever you feel right in the web.config file as follow:
<authentication mode="Forms"> <forms loginUrl="YOUR_LOGIN_PAGE" timeout="2880"/> </authentication>
The secret key will have to be saved somewhere (like a DB) do that is can be used when the user comes back to your website. Of course, there should be a Logout button somewhere on your website. When user asks to log out, simply call
1 | FormsAuthentication.SignOut() |
to have the cookie removed. Note: next time the user will want to come back, he will have to go through the Twitter OAuth authorization process again, since that’s the only way your app will be able to authenticate the user.
Custom ASP.NET MVC Authorization with Facebook Connect
Action filters are an interesting concept in ASP.NET MVC. The point with action filters is that you can basically intercept a call to an ASP.NET MVC action and execute some code before the action’s code is executed. The ‘Authorize’ action filter is often used in Forms Authentication to make sure that an action reserved to a member is not executed by a non-member. When it come to using this feature with Facebook Connect applications, things get a little bit dirty. In this article, I will explore some contradicting aspects of Facebook Connect in regards to its integration with Forms Authentication and propose a solution which is based on implementing a custom ASP.NET MVC authorization.
Forms authentication is a cookie-based authentication method. The thing is that Facebook Connect also uses cookies as a mean of authentication. A Facebook cookie contains a session key which is valid for the session. Facebook API calls must be done with this session key to associate actions to a Facebook account.
Now, if a developer wants to use both Forms Authentication and Facebook cookies to handle a session, there will be countless issues of data incoherence to handle (ex: Facebook sessions expire when the browser is closed, but not Forms Authentication sessions).
The solution is to not use Forms Authentication or any other ASP.NET authentication at all, but use a custom authorization class which wraps Facebook’s session cookie. To do so, create a new class like with the following code:
public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { if (Validate_Facebook_Connect_Cookie()) return true; httpContext.Response.Redirect("Facebook_Connect_URL"); return false; } }
The ‘Validate_Facebook_Connect_Cookie()‘ function should look into the cookie and verify that the user is correctly authenticated. Now, all you have to do is to add the ‘[CustomAuthorize]‘ attribute to those actions that need authorization.
How to Connect Your ASP.NET MVC Twitter Application to Twitter OAuth
For those who are familiar with Facebook Connect, Twitter has a similar service. It’s called Twitter OAuth. Twitter applications that use Twitter OAuth do not ask for password as opposed to other Twitter Applications. This is a plus for user privacy and inspires confidence when a new visitor wants to use your app. Personally, I am reluctant in providing my login and password to some website I stumbled upon but that I have never heart of. So when I developed a Twitter application called Upruf, I used Twitter OAuth. You can take a look at it to see how Twitter OAuth works with ASP.NET MVC. In this article, I’ll show a simple way to connect your ASP.NET MVC app to Twitter OAuth.
Before starting, make your life easier and get one of those OAuth .NET libraries or classes and add it to your project. You will avoid a lot of headache in dealing with ‘HttpWebRequest’ class and interoperability issues with different sites. There is a lot of them out there, so you need to find one that suites your needs. I’m not going to recommend one since changes to Twitter’s own implementation of OAuth could break how a .NET library works. Also, don’t forget that you will have to provide your Twitter application’s public and secret keys to the classes or the library. Nevertheless, if your mad about doing everything yourself, the Twitter OAuth process is explained enough in this article for you to be able to do so.
First, create a new controller and call it Twitter. Of course you can give any other name, and you don’t even have to create a new controller if you don’t want to. In this example we will suppose that a new controller is created, as I find that things are cleaner in this way. In this controller, create a new action called ‘CallBack’ (Twitter server will request this action after the user has authorized your application to perform status updates).
Second, in the Index function of your new controller, initiate the authorization process by requesting ‘http://twitter.com/oauth/request_token‘. Twitter server will respond back with an OAuth Token. If you are using an OAuth .NET library, you might have a function that covers this as well as the next step in one single function call (skip the next step if it is your case).
Third, you will have to extract the OAuth Token from the previous response and request for ‘http://twitter.com/oauth/authorize?oauth_token=The_OAuth_Token‘ where The_OAuth_Token is the extracted token. You might have to add the URL to your callback action which make the request look something like this: ‘http://twitter.com/oauth/authorize?oauth_token=The_OAuth_Token&oauth_callback=URL_To_Your_CallBack‘. This will get you to the point where the user is shown with the Twitter authorization page. After the user has authenticated and allowed your Twitter App to perform status updates, Twitter will call the ‘CallBack’ action (which is the URL_To_Your_CallBack).
Fourth, In your ‘CallBack’ action, you will first need to make a request to ‘http://twitter.com/oauth/access_token‘ to get the OAuth secret token. Again, OAuth .NET libraries should have a function for this. Once you have the secret token, request for user information with ‘http://twitter.com/account/verify_credentials.xml‘ to which Twitter server will respond with an XML answer containing user credentials.
At this point, you can use Twitter API to do all those things that you can do with it. Remember, the secret token must be provided with every request to the Twitter API so that they are linked to the right Twitter account. Since Twitter API uses the REST architecture, objects do not have a life time across multiple HTTP requests. This means that you will have to save the secret key somewhere (in Session object for example) to be able to perform API calls for the span of the user session. Also, secret keys do not have a expiration period. This means that you can use a secret key for as long as you want to. This characteristic will introduce a few particularities to consider in regards to ASP.NET Membership and Form Authentication. I will cover this aspect in a future article.
8 SEO Reflexes for Web Developers
One efficient way of implementing good SEO is to have web developers integrate SEO while coding. Here is a list of habits every web developer should have when coding website’s server side:
- Have a different title and meta-tags for each page. You should have a set of keywords for every page and have them incorporated in the page title before the company name.
- Use title tag for links and use those keywords in it. Use keywords in the anchor text also.
- Use h1, h2, h3, bold and italic around keywords as much as possible.
- Use the alt tag for images and use keywords to name the image.
- Use search engine friendly URLs.
- Have a sitemap.xml for search engines.
- Don’t overuse Ajax. Since Ajax content is dynamic, some of the page’s content will not be seen by the spider.
- Don’t use Flash for menus. The spider doesn’t look at Flash.
Integration of Facebook Connect With ASP.NET MVC
If you are a Facebook Application developer working classical ASP.NET, you are probably familiar with the Facebook Developer Toolkit. This tool comes with a great set of server side controls that ease a lot of the developer’s job. But if you are like me and that you want to enjoy ASP.NET MVC, then you cannot use those server side controls that easily, so MVC Addon project might be of great help. The MVC Addon will help overcome differences in the rendering and resource requesting differences between classical ASP.NET and ASP.NET MVC.
But when it comes to integrating Facebook Connect with ASP.NET MVC, a few things need to be changed from steps explained in classical ASP.NET tutorials. This article is about overcoming those difficulties. So lets get started.
First, you will need to add the following code to your Site.Master file:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"> </script> <script src="/Scripts/fbconnect.js" type="text/javascript"></script> <script type="text/javascript"> FB.init("YOU_API_KEY", "xd_receiver"); </script>
Then, you should create a new controller called ‘xd_receiver’ and add the following code to its Index View (which should not derive from the master page):
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Cross-Domain Receiver Page</title> </head> <body> <script src="http://static.ak.facebook.com/js/api_lib/v0.4/XdCommReceiver.js?v2" type="text/javascript"></script> </body> </html>
Finally, you should add the following code to render the Facebook Connect login button:
<fb:login-button onlogin="facebook_onlogin_ready();"></fb:login-button>We’re done! When the user clicks on the Facebook Connect button, the Facebook login window pops up. After the user has entered the login information, the pop up closes and your website’s browser window will refresh. From here you can start reading the cookie for the user information and other stuff.
20 Must Haves For All Websites
Project after project, certain things seem to be coming over and over again. We can say that they are standards and become must haves for all websites. Some of them are little things but they make a big difference and give a professional look to the website.
- Usable interface: this is different from a good looking design. The aim here is to provide the service in a simple yet optimal way. Every little detail must be thought of when this is done. The goal is to 1) provide much information with little effort from user 2) answer needs with as little functions and clicks as possible.
- Navigation bars: primary above the fold and repeat in the footer. It is part of a usable interface. It is often useful to go from one section to another or to come back to our initial footsteps.
- Good visual design: this is about having an appealing look, but also one that fits with the service. For example, the best looking design for a e-commerce would be useless if we’re building a social networking website.
- Separate CSS from content: this is a big helper if its done at the beginning of the project. Designs need to be updated and it is much easier and cheaper (later) to have separate files for content and design.
- ‘Contact US’ page: Often overlooked, but a big irritation for the user when it has to look for contact information and not be able to find it.
- Privacy policy: this is common good behavior and is a big issue for consumers. Every website should let its users know how information is collected about them.
- Copyright notice: nobody want to innovate for free. If copyright notice is not there, it night indicate that there is little creative effort behind the website.
- FAQ: this is a great way to answer common questions related to a website and is always very useful. The easiest way to start with the FAQ is note questions and answers from the first people who see the website.
- Subscribe: don’t be cheap and have RSS feeds, newsletters, etc. You must feed your users with information.
- ‘About Us’ page: Let people know what the website is there for. Also a good place to present the team behind the service.
- Digital Assets: Videos, pics, podcasts. All these are trademarks of modern professional websites.
- Blog: This is great way to provide news and updates to your users. It has to be thought of a parallel service to you main service. The more information you will offer about your service, the more it will be adopted. Also, it is a great way to be in touch with your customers.
- Feedback script: There are a couple of good scripts for user feedback. It is a great tool and it is highly adopted by new websites.
- Search: Always good to have this and avoid a lot of headache when it comes to looking around a dynamic website. A lot of great tools are available to ease the job.
- Meaningful content: this tip might look like a waste of time, but people often forget to provide meaningful text. It is as if we often think of design as being more important that content. Don’t forget that ‘content is king’.
- Search engine optimized content: This one must be done in concert with previous tip. When content is created, it must be done with the search engine in mind. There is much art to be used here to not alter the literary quality of the content.
- Sitemap: helps website crawling a lot. This is in line with search engine optimization.
- Social bookmarking links: social media optimization is now part of every marketing campaign.
- Cross browser compatibility: Not everyone is using IE anymore. Sometimes, people use older browser like IE 6. Lets get visitors come back by being compatible with their browser of choice.
- Web analytics: building a site is about incremental improvements. Web analytics help invest your improvement effort in the right direction by showing how people use your website.

Posted by Ahmad Barirani in
