Tag Archives: mvc

Data Annotations MVC Validation

If you are looking for the attribute or data annotation to be used in your MVC model e.g. to validate email addresses you may in reality be looking for the DataType Enumeration (remember it next time you google it).

Actually, the EmailAddress data type doesn’t work for the validation. I use my own regex:

[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Not a valid e-mail")]

This is just a little note for me, as I lost quite some time to find this.

UPDATE: the regular expression above is wrong, email like first.last@my-company.com was treated as invalid (to be updated when I have free time).

This works (with .net 4.5):

public string Email { get; set; }

C# send a mail using razor views as template

If you are looking for a way to send an e-mail via C#, you may find some code examples such as Send e-mail via SMTP using C#. I used such a solution in many projects, by creating an HTML file in a separate folder, reading its contents, do text replacements and then send the message. That solution always worked fine. I liked my old school solution also because I could edit the HTML file and preview it by clicking it or pointing the browser to its location.

Lately I found a more elegant solution for my MVC projects with a library called Postal. You can install it via NuGet, create a view containing your email template, then, in your controller, you can send a mail just with a few lines of code, as explained in the Getting Started example.

At work I coded a few mailers (to send a reminder, or an occasional newsletter) and they worked quite fast with my old school system. Also with Postal, results have been quite good.

If you are interested in performance, I can code a few tests to see how much each solution can scale. Updates will come, stay tuned.

By the way, if you are interested in creating responsive emails, you may have a look at Bootstrap Template for HTML Email and if you want to convert an existing HTML into a mail friendly HTML (all CSS styles inline), check Premailer.

MVC 5 for Visual Studio 2012

If you are still using Visual Studio 2012 and are looking for a way to have intellisense for your views made for razor 3, if you want to add a new view and a new controller with the proper menu entries in visual studio you probably noticed that with things don’t work as they should.

Simply install the following 2 components:

In case the links don’t work, check the original articles where I’ve found all the necessary information (thanks to them):

After installing these 2 components, you’ll finally be able to work on MVC5, just as you were used with MVC 4. Check these screenshots:


When you right click on “Controllers” and select “Add” you can now select “Controller…”


When you right click on your Views folder and then select “Add” you can now select “View…” as well as new entries (see MVC 5 View options at the bottom)


When you add a View, you can select a Model class and a Data context class, scaffolding will work also with Entity Framework 6


Visual Studio 2012 Templates

UPDATE: I added a GitHub repository and included my updates to the MVC4 Empty, Basic and MvcApplication templates. Feel free to contribute. See in the Download chapter.

So you use Visual Studio 2012, NuGet, you create a new project from the standard MVC 4 template and then you update all packages you need, or click on “Update All” and then “downgrade” one (e.g. jQuery 2.x to jQuery 1.x)?

If you need to update everything and downgrade just one package (in example jQuery), you can use the Package Manager Console and issue these 2 commands (first force the uninstallation of jQuery even if it’s needed by other libraries, then install the specific version you need):

Uninstall-Package jQuery -Force
Install-Package jQuery -Version 1.10.2

If you want your templates to be always updated, you may want to edit them directly (as usual, do a backup first), so that when you create a new project you won’t need to update all the NuGet packages. You may be interested in these 2 locations:

  • Templates folder: C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ProjectTemplates\CSharp\Web\1033
  • Packages folder: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Packages

In the Templates folder you can edit the *.vstemplate file and put the package versions you want. For the javascript files, remember also to update the Scripts\_references.js file. For the references, remember also to update the *.csproj (project) file. Some Libraries require you to update also the web.config file.

In the Packages folder you need to copy the nupkg file and the folder containing the package (take the packages from a new visual studio solution you create).

This seems complicated but once you updated your favorite template, it’ll be a piece of cake to maintain it.


To update your existing Visual Studio 2012 templates, just overwrite them with the files you find in my GitHub repository (do a backup of the originals, just in case).

If your favorite template is not here, sorry about that. I update only the templates I use the most for my projects. Feel free to share your updates (at best commit your changes directly in my github repository).

Other interesting resources for Visual Studio 2012

MVC Dropdownlist for enum

If you wanna display a dropdown list for an enumeration. ASP.NET MVC – Creating a DropDownList helper for enums is a great tutorial to achieve that.

However, if you wanna save in your DB the integer and not the text value, check Best method to store Enum in Database.

I had an enum similar to this:

public enum Sources
	Internet = 20,
	Space = 999

In my model class, I ended to use this code:

[HiddenInput(DisplayValue = false)]
public virtual int SourceId
		return (int)this.Source;
		Source = (Sources)value;
public Sources Source { get; set; }

Hope this helps.

Solution for jquery unobtrusive ajax live error

So you get an error from jquery.unobtrusive-ajax.min.js:

TypeError: $(…).live is not a function?

If you, like me, just upgraded in Visual Studio all NuGet packages included in your MVC project, you may probably encounter this error because the live() function is not available anymore in jquery 1.9, but still being called by .

The problem is that jquery.unobtrusive-ajax.min.js (jQuery Unobtrusive Ajax 2.0.20710.0 at the moment of writing) is calling the live() function in several places.

Here the solution: replace all occurrences of “live(” with “on(“, save and that’s it (source: stackoverflow)


jQuery Unobtrusive Ajax was upgraded and you can use the newest version with the latest jquery 1.x version.

Multilanguage MVC4 or MVC5 website

So you want to create a multilingual project in MVC4 or MVC5? You are new to ASP.NET MVC and you are looking for a working solution, easy to understand and easy to implement? You are in the right place. This solution has been used for a couple of live websites and it worked quite well. Also the Frontend Developer that worked with me was quite happy with the solution. Read on to understand why.

You will find online a couple of tutorials and approaches. One I liked and followed is Creating a Bilingual ASP.NET MVC 3 Application – Part 2: it offers a working culture detection based on the user browser’s settings and it allows the user to browse the site also by entering in the url -just after the domain name- the language abbreviation (like this: http://www.example.com/en/Home/Index ). The solution in the above tutorial allows the developer to save the translations in .resx files (same principle for LocalResources and GlobalResources).

However, the Cultural View Engine for MVC tutorial (or better: Custom View Engine for Localized Views with ASP.NET MVC Razor – for razor cshtml pages) offers the same browsing routes and the possibility to save the translations directly in the view files, making the editing much more user friendly than editing the .resx files in Visual Studio (which, for long and formatted texts, is not user friendly at all).

When I studied these 2 approaches/tutorials, I decided to mix them, making the developer life much easier and flexible.

Imagine the following scenario:

  • Global.resx file for all the common translations for classic UI labels, buttons, tooltips etc.
  • a default ~/Views folder containing the main views and partial views (e.g. Index.cshtml, About.cshtml, _Header.cshtml, _Footer.cshtml) with localized content taken from the .resx files, like this @Global.FooterText
  • some views containing the content not as variable like @Global.FooterText but copied and pasted there directly e.g. “Copyright Foo Bar 2013”, saved e.g. in Example.cshtml
  • the same views as above, with the same name as above and a language suffix e.g. Example.de.cshtml and content translated directly in that file (in this example, “de” is for German)


My solution


  • MultilanguageMVC4-2013.10.07a.zip (use this as reference only. Create your own project in Visual Studio 2013 in MVC5 to have all the updated packages and dependencies, bootstrap etc.)
  • Update 2016-05-13 I didn’t check it but you may have a look at Xavier educa02 on github (repository based on this work)

Note: in the Areas you can’t have a controller with the same name of a standard controller (or vice-versa). Every controller must have a unique name.

You may find these 2 helpers quite handy (I use GetLanguage in my controllers when I need to process contents based on the language, in example to build an URL I have to insert in a mail sent to the user, or similar things):

  • CultureManager.GetLanguage()
  • CultureManager.GetCulture()

To use/implement this solution in your own project in your solution you need about 5 Minutes (+ a few more minutes to add new languages or remove the ones you do not want to support). Just follow this simple procedure:

  • copy all the files you find under “Code” and put them in a separate class library (and add a reference to it), or copy the “Code” folder directly in your project.
  • Check the modifications to the global.asax.cs file and apply them to your global.asax.cs file (and update your default route in case it’s not Home/Index).
  • If you want more languages or remove some from the default ones I added (en, de, fr, it) you must edit the CultureManager.cs file. Check the constants at the top and the method InitializeSupportedCultures(). If you need more precision in the culture (in my case I use only the 2 letters ISO abbreviation) you may do some refactoring.


My solution is based on these 2 tutorials:

I downloaded and updated the first tutorial solution and added the LocalizedViewEngine.cs from the 2nd tutorial. Then updated the global.asax.cs file accordingly.

As some people asked for it, I added also an example with Areas. If you don’t need areas, simply delete the “Areas” folder, save all and re-compile.



Update 2015-02-19
Seems that this blog post is still helpful. Good news, this solution works of course also with MVC5. Don’t update my demo project to MVC5, start a fresh one and follow the procedure to add multi-language views support.

Update 2013-10-21
Added some more useful information on how to use this solution. Hopefully it should be quite easy to implement this in your solution.

Update 2013-10-07
As some people asked for it, I added an example with Areas. I added an Area called “Admin”, a controller called “Account” and 2 test Views: Index and Test. I added a localized Index.de and for Test I used the .resx resources. To register the new area and make it work with my multi language support, see Areas\Admin\AdminAreaRegistration.cs. Hope this helps.

Update 2013-06-05
I’m not 100% about this, but my solution can lead to caching problems.

Symptom: after changing the language to xx I keep seeing the contents of my main View PageFoo.cshtml and not the contents in PageFoo.xx.cshtml.

Solution: I needed -for my production website- to keep the debug option in the web.config file, more precisely in the tranform web.config.live in Visual Studio I had to keep this (as I use the publish function):

<compilation xdt:Transform="RemoveAttributes(debug)" />

If you don’t have a transform file, then the option in the web.config file has to be:

<compilation debug="true" targetFramework="4.0" />