<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule"
>

<channel>
	<title>Martin Normark&#039;s blog</title>
	<atom:link href="http://martinnormark.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://martinnormark.com</link>
	<description></description>
	<lastBuildDate>Fri, 17 May 2013 12:39:55 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
		<item>
		<title>Backbone and ASP.NET MVC: Use Nullable types as Id</title>
		<link>http://martinnormark.com/backbone-and-asp-net-mvc-use-nullable-types-as-id/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/backbone-and-asp-net-mvc-use-nullable-types-as-id/#comments</comments>
		<pubDate>Wed, 05 Dec 2012 22:17:46 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[backbone.js]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=465</guid>
		<description><![CDATA[<p>As a side note to my blog post about renaming the idAttribute in Backbone when using it with ASP.NET (MVC), this post continues with the Id attribute. The Id attribute in Backbone is very important. Backbone uses it to determine if an object is new, or already existed. Collections use it to determine if it already contains any given object. So I ran into a problem in a situation where my model required a lot of &#8220;supporting data&#8221; before it was saved. To add this data, I decided to create the models on the server and add it to a collection (since there were a whole list of them). No matter how many models I added to the list, only the first one was rendered. Why? Because my model on the server was using a non-nullable Integer as its Id property &#8230; <a href="http://martinnormark.com/backbone-and-asp-net-mvc-use-nullable-types-as-id/">Continued</a></p><p>The post <a href="http://martinnormark.com/backbone-and-asp-net-mvc-use-nullable-types-as-id/">Backbone and ASP.NET MVC: Use Nullable types as Id</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>As a side note to my blog post about <a title="Backbone and ASP.NET MVC: Rename the ID attribute" href="http://martinnormark.com/backbone-asp-net-mvc-rename-idattribute">renaming the idAttribute in Backbone</a> when using it with ASP.NET (MVC), this post continues with the <a href="http://backbonejs.org/#Model-idAttribute">Id attribute</a>.</p>
<p>The Id attribute in Backbone is very important. Backbone uses it to determine if an object is new, or already existed. Collections use it to determine if it already contains any given object.</p>
<p>So I ran into a problem in a situation where my model required a lot of &#8220;supporting data&#8221; <em>before</em> it was saved. To add this data, I decided to create the models on the server and add it to a collection (since there were a whole list of them).</p>
<p>No matter how many models I added to the list, only the first one was rendered. Why? Because my model on the server was using a non-nullable Integer as its Id property like this:</p>
<pre>public class Account
{
	public int Id { get; set; }
}</pre>
<p>So of course, all the models returned from the server had an Id of zero! And of course, Backbone thought that they were all the same instance since they shared the same Id.</p>
<h2>Small change, huge impact</h2>
<p>Talk about a single character making a huge impact!</p>
<p>By adding the silly question mark to the Id property, everything was working. That&#8217;s because a Nullable integer is not added to the JSON returned by the server, and Backbone then knows that this model does not exist!</p>
<p>The post <a href="http://martinnormark.com/backbone-and-asp-net-mvc-use-nullable-types-as-id/">Backbone and ASP.NET MVC: Use Nullable types as Id</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/backbone-and-asp-net-mvc-use-nullable-types-as-id/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>3 Reasons Why Dedicated ViewModels in ASP.NET MVC is a *MUST*</title>
		<link>http://martinnormark.com/use-dedicated-viewmodels-asp-net-mvc/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/use-dedicated-viewmodels-asp-net-mvc/#comments</comments>
		<pubDate>Tue, 04 Dec 2012 22:55:01 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=463</guid>
		<description><![CDATA[<p>I&#8217;d argue that using dedicated view-models in ASP.NET MVC (or any other MVC framework) is one of the things that has changed the way I work for the better. And for the better I mean more maintainable code, better designed code, more robust code &#8212; just better in all ways measurable. Here are three reasons why you should use truly dedicated view-models for any view in ASP.NET MVC. 1. Abstract code beyond your control If you work on a web team, that is part of a larger team you cannot expect to always have the entire back-end ready at the time you want to start coding a feature for the front-end. But why wait? Even if you don&#8217;t have the service layer, the domain models or the database ready, you can just easily create dummy instances of your view-model in a controller and &#8230; <a href="http://martinnormark.com/use-dedicated-viewmodels-asp-net-mvc/">Continued</a></p><p>The post <a href="http://martinnormark.com/use-dedicated-viewmodels-asp-net-mvc/">3 Reasons Why Dedicated ViewModels in ASP.NET MVC is a *MUST*</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>I&#8217;d argue that using dedicated view-models in ASP.NET MVC (or any other MVC framework) is one of the things that has changed the way I work for the better. And for the better I mean more maintainable code, better designed code, more robust code &#8212; just better in all ways measurable.</p>
<p>Here are three reasons why you should use truly dedicated view-models for any view in ASP.NET MVC.</p>
<h2>1. Abstract code beyond your control</h2>
<p>If you work on a web team, that is part of a larger team you cannot expect to always have the entire back-end ready at the time you want to start coding a feature for the front-end. But why wait? Even if you don&#8217;t have the service layer, the domain models or the database ready, you can just easily create dummy instances of your view-model in a controller and return that to the view.</p>
<p>You can get started coding the UI, the JavaScript, maybe hook up your Backbone models or anything similar.</p>
<p>You are also in complete control of the design of the view-models, and it often turns out that they end up a hell of a lot different from the domain models.</p>
<h2>2. Keep view oriented data annotations out of the domain model</h2>
<p>You want to use both validation attributes, UIHints, template information and a lot of other view oriented stuff that should stay inside the MVC project.</p>
<p>The problem is that if you throw all these things on the domain model, you suddenly have a dependency on ASP.NET MVC and Razor which means that you must add reference to these dependencies from your lower tiers. Not good!</p>
<h2>3. Defend your JavaScript from outside changes</h2>
<p>JavaScript is playing a bigger and bigger part in modern web development. So the more JavaScript your write that manipulates your view-models, the more exposed you become to outside changes.</p>
<p>Having a dedicated view-model makes you in control, and not the DBA or any other dude who doesn&#8217;t care about the front-end.</p>
<h2>How to avoid repeating yourself</h2>
<p>It&#8217;s probably the worst argument against view-models, that you end up repeating the domain-models. If you think that, you&#8217;ve missed something.</p>
<p>The point of a view-model is to make it as closely tied to the view as possible. This will make the view a lot more simple, which is a good thing.</p>
<p>For mapping a domain-model to a view-model and vice-versa, I use <a href="http://automapper.org/">AutoMapper</a> which is extremely simple, yet powerful.</p>
<p>The post <a href="http://martinnormark.com/use-dedicated-viewmodels-asp-net-mvc/">3 Reasons Why Dedicated ViewModels in ASP.NET MVC is a *MUST*</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/use-dedicated-viewmodels-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Backbone and ASP.NET MVC: Rename the ID attribute</title>
		<link>http://martinnormark.com/backbone-asp-net-mvc-rename-idattribute/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/backbone-asp-net-mvc-rename-idattribute/#comments</comments>
		<pubDate>Mon, 03 Dec 2012 21:22:09 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=461</guid>
		<description><![CDATA[<p>In Backbone, a model&#8217;s ID attribute is vital in the way Backbone handles models and collections. In a collection, you can call get with an ID and you&#8217;ll get back the model. The thing is, naming conventions across languages does not always agree. In .Net properties are named in PascalCase. In JavaScript camelCase is the standard, so naturally this leads to a conflict when your model in Backbone names the ID attribute id, and the corresponding domain model on the server side is named Id. I was using an ASP.NET MVC controller to return a collection of Accounts, but when it hit the client, got changed and later saved, the ID was lost and the model was created as a new instance in the database. The problem was that when Backbone fetched the collection, and automatically turned the objects in &#8230; <a href="http://martinnormark.com/backbone-asp-net-mvc-rename-idattribute/">Continued</a></p><p>The post <a href="http://martinnormark.com/backbone-asp-net-mvc-rename-idattribute/">Backbone and ASP.NET MVC: Rename the ID attribute</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>In Backbone, a model&#8217;s ID attribute is vital in the way Backbone handles models and collections. In a collection, you can call get with an ID and you&#8217;ll get back the model.</p>
<p>The thing is, naming conventions across languages does not always agree. In .Net properties are named in PascalCase. In JavaScript camelCase is the standard, so naturally this leads to a conflict when your model in Backbone names the ID attribute id, and the corresponding domain model on the server side is named Id.</p>
<p>I was using an ASP.NET MVC controller to return a collection of Accounts, but when it hit the client, got changed and later saved, the ID was lost and the model was created as a new instance in the database.</p>
<p>The problem was that when Backbone fetched the collection, and automatically turned the objects in the array into instances of Account &#8212; Backbone was expecting to find every model&#8217;s ID in the id property, which did not exist. And on the server, it uses Id to know if this model is new or already exists.</p>
<h2>Change the idAttribute</h2>
<p>It turns out that Backbone is designed for this.</p>
<p>Whenever you define your models, you need to set the value of the idAttribute property like this:</p>
<pre>var Account = Backbone.Model.extend({
	idAttribute: "Id"
});</pre>
<p>But that&#8217;s a bit annoying since you&#8217;ll have to remember this on each and every model. And you need to define your own model every time, you can&#8217;t just create a new instance of the stock Backbone.Model class.</p>
<p>But with JavaScript being the awesome language that it is, you can change the prototype like this:</p>
<pre>Backbone.Model.prototype.idAttribute = "Id";</pre>
<p>And now you can totally forget about this, and let Backbone handle IDs properly!</p>
<p>The post <a href="http://martinnormark.com/backbone-asp-net-mvc-rename-idattribute/">Backbone and ASP.NET MVC: Rename the ID attribute</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/backbone-asp-net-mvc-rename-idattribute/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Entity Framework: Update single column</title>
		<link>http://martinnormark.com/entity-framework-update-single-column/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/entity-framework-update-single-column/#comments</comments>
		<pubDate>Sun, 02 Dec 2012 21:44:15 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[entity framework]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=459</guid>
		<description><![CDATA[<p>Yesterday I blogged about how to delete a detached entity using Entity Framework 5 by only using its Id. A common practice in many applications today is to not actually delete the entity from the database, but instead mark it as deleted and make sure your data access layer filters out those &#8220;deleted&#8221; items when selecting. So I wanted to implement a general &#8220;delete&#8221; method that would update the DateDeleted column of an entity without touching any other column. Again I use a detached entity, so the trick is to only mark the DateDeleted column as modified, and not the entire entity. public bool DeleteEntity(T entity) where T : ModelBase { entity.DateDeleted = DateTime.UtcNow; this._databaseContext.Set().Attach(entity); this._databaseContext.Configuration.ValidateOnSaveEnabled = false; this._databaseContext.Entry(entity).Property(m =&#62; m.DateDeleted).IsModified = true; int recordsAffected = this._databaseContext.SaveChanges(); this._databaseContext.Configuration.ValidateOnSaveEnabled = true; return recordsAffected == 1; } Notice how I disable validation, and &#8230; <a href="http://martinnormark.com/entity-framework-update-single-column/">Continued</a></p><p>The post <a href="http://martinnormark.com/entity-framework-update-single-column/">Entity Framework: Update single column</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Yesterday I blogged about <a href="http://martinnormark.com/entity-framework-delete-record-by-id-detached-entity">how to delete a detached entity</a> using Entity Framework 5 by only using its Id.</p>
<p>A common practice in many applications today is to not actually delete the entity from the database, but instead mark it as deleted and make sure your data access layer filters out those &#8220;deleted&#8221; items when selecting.</p>
<p>So I wanted to implement a general &#8220;delete&#8221; method that would update the DateDeleted column of an entity without touching any other column.</p>
<p>Again I use a detached entity, so the trick is to only mark the DateDeleted column as modified, and not the entire entity.</p>
<pre>public bool DeleteEntity(T entity) where T : ModelBase
{
	entity.DateDeleted = DateTime.UtcNow;

	this._databaseContext.Set().Attach(entity);
	this._databaseContext.Configuration.ValidateOnSaveEnabled = false;

	this._databaseContext.Entry(entity).Property(m =&gt; m.DateDeleted).IsModified = true;

	int recordsAffected = this._databaseContext.SaveChanges();

	this._databaseContext.Configuration.ValidateOnSaveEnabled = true;

	return recordsAffected == 1;
}</pre>
<p>Notice how I disable validation, and then enable it after saving the changes. This is because I don&#8217;t want to load the entity before changing DateDeleted. I want to use only the Id, so I want to avoid having to fulfill all validation rules on an entity.</p>
<p>All my model classes derive from the ModelBase class, which looks like this:</p>
<pre>public abstract class ModelBase
{
	public ModelBase()
	{
		this.DateCreated = DateTime.UtcNow;
	}

	public DateTime DateCreated { get; set; }

	public DateTime? DateModifed { get; set; }

	public DateTime? DateDeleted { get; set; }
}</pre>
<p>To &#8220;delete&#8221; an entity, I can instantiate an entity, give it an Id, and call the delete method:</p>
<pre>Account account = new Account { Id = 123 };

DeleteEntity(account);</pre>
<p>The post <a href="http://martinnormark.com/entity-framework-update-single-column/">Entity Framework: Update single column</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/entity-framework-update-single-column/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Entity Framework: Delete Entity by Id &#8211; Using Detached Instance</title>
		<link>http://martinnormark.com/entity-framework-delete-record-by-id-detached-entity/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/entity-framework-delete-record-by-id-detached-entity/#comments</comments>
		<pubDate>Sat, 01 Dec 2012 12:00:42 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[entity framework]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=457</guid>
		<description><![CDATA[<p>Entity Framework 5, with the Code First approach can do some pretty powerful things without much effort. Create your model classes, and it spins up a brand new and shiny database for you. But sometimes you do need to tweak a few things in order to achieve what you want. For example, I don&#8217;t want to load an entity before I can delete it. What&#8217;s the point? Say I have a list of Accounts on a webpage, with a shiny delete button that makes an AJAX call to an MVC controller, (or Backbone model, that hits the web backend). In that situation I&#8217;ll only have the Id of the entity, which should be enough to delete it. Attach, Delete To delete only by Id, you need to create a dummy instance of your model with the Id you wish to &#8230; <a href="http://martinnormark.com/entity-framework-delete-record-by-id-detached-entity/">Continued</a></p><p>The post <a href="http://martinnormark.com/entity-framework-delete-record-by-id-detached-entity/">Entity Framework: Delete Entity by Id &#8211; Using Detached Instance</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/data/ef.aspx">Entity Framework</a> 5, with the <a href="http://www.codeproject.com/Articles/468777/Code-First-with-Entity-Framework-5-using-MVC4-and">Code First</a> approach can do some pretty powerful things without much effort. Create your model classes, and it spins up a brand new and shiny database for you.</p>
<p>But sometimes you do need to tweak a few things in order to achieve what you want. For example, I don&#8217;t want to load an entity before I can delete it. What&#8217;s the point? Say I have a list of Accounts on a webpage, with a shiny delete button that makes an AJAX call to an MVC controller, (or<a title="Backbone.js Compatible Routes for, non-Web API, ASP.NET MVC projects" href="http://martinnormark.com/backbone-js-compatible-routes-aspnet-mvc"> Backbone model, that hits the web backend</a>). In that situation I&#8217;ll only have the Id of the entity, which should be enough to delete it.</p>
<h2>Attach, Delete</h2>
<p>To delete only by Id, you need to create a dummy instance of your model with the Id you wish to delete.</p>
<pre>Account account = new Account { Id = 123 };</pre>
<p>Then, with EF5 you will have to attach the entity to its DbSet.</p>
<pre>this.DbContext.Accounts.Attach(account);</pre>
<p>Then mark it as deleted, and save the changes.</p>
<pre>this.DbContext.Entry(account).State = EntityState.Deleted;

this.DbContext.SaveChanges();</pre>
<p>&nbsp;</p>
<p>The post <a href="http://martinnormark.com/entity-framework-delete-record-by-id-detached-entity/">Entity Framework: Delete Entity by Id &#8211; Using Detached Instance</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/entity-framework-delete-record-by-id-detached-entity/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Backbone.js Compatible Routes for, non-Web API, ASP.NET MVC projects</title>
		<link>http://martinnormark.com/backbone-js-compatible-routes-aspnet-mvc/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/backbone-js-compatible-routes-aspnet-mvc/#comments</comments>
		<pubDate>Fri, 30 Nov 2012 08:53:26 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[backbone.js]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=433</guid>
		<description><![CDATA[<p>Backbone.js has become my JavaScript MV* framework of choice (you do use a JavaScript MV* framework, to structure JavaScript, right?). I find myself using ASP.NET MVC for less and less that has something to do with views, and other stuff that belongs on the client. The server, being ASP.NET MVC, is the new backend now a days. I&#8217;m sure that&#8217;s how Microsoft sees it as well, with the release of Web API. When using models in Backbone, and specifying the urlRoot setting, Backbone will automatically construct URLs to do CRUD operations against your server. It uses RESTful URLs, and regular ASP.NET MVC controllers are not compatible with those out of the box. Consider this Backbone model and collection: var Account = Backbone.Model.extend({ urlRoot: "/accounts" }); var AccountCollection = Backbone.Collection.extend({ model: Account, url: "/accounts" }); When you save a new Account, Backbone will make a POST &#8230; <a href="http://martinnormark.com/backbone-js-compatible-routes-aspnet-mvc/">Continued</a></p><p>The post <a href="http://martinnormark.com/backbone-js-compatible-routes-aspnet-mvc/">Backbone.js Compatible Routes for, non-Web API, ASP.NET MVC projects</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://backbonejs.org/">Backbone.js</a> has become my <a href="http://addyosmani.com/blog/understanding-mvc-and-mvp-for-javascript-and-backbone-developers/">JavaScript MV* framework</a> of choice (you do use a JavaScript MV* framework, to <a title="10 Ways to (re) Structure JavaScript" href="http://martinnormark.com/10-ways-structure-javascript">structure JavaScript</a>, right?). I find myself using ASP.NET MVC for less and less that has something to do with views, and other stuff that belongs on the client.</p>
<p>The server, being ASP.NET MVC, is the new backend now a days. I&#8217;m sure that&#8217;s how Microsoft sees it as well, with the release of Web API.</p>
<div id="attachment_454" class="wp-caption alignnone" style="width: 650px"><a href="http://martinnormark.com/wp-content/uploads/2012/11/backbone-routes-aspnet-mvc.jpg"><img class="box  " title="Routes" src="http://martinnormark.com/wp-content/uploads/2012/11/backbone-routes-aspnet-mvc.jpg" alt="" width="640" /></a><p class="wp-caption-text"><em>cc by-nc-nd Bruno Monginoux <a href="www.landscape-photo.net">www.photo-paysage.com</a> &amp; <a href="www.landscape-photo.net">www.landscape-photo.net</a></em></p></div>
<p>When using <code>models</code> in Backbone, and specifying the <code>urlRoot</code> setting, Backbone will automatically construct URLs to do CRUD operations against your server. It uses RESTful URLs, and regular ASP.NET MVC controllers are not compatible with those out of the box.</p>
<p>Consider this Backbone model and collection:</p>
<pre>var Account = Backbone.Model.extend({
	urlRoot: "/accounts"
});

var AccountCollection = Backbone.Collection.extend({
	model: Account,

	url: "/accounts"
});</pre>
<p>When you save a new Account, Backbone will make a <code>POST</code> request to your server expecting to hit your <code>AccountsController</code>. But with regular MVC controllers (non-Web API, that is) the routing won&#8217;t succeed, since the default <code>{controller}/Index</code> action only works with the default, parameter less <code>GET</code> request.</p>
<p>You might think that this controller will work:</p>
<pre>public class AccountsController : Controller
{
	[HttpGet]
	public JsonResult Index()
	{
		List accounts = new List();
		accounts.Add(new Account { Id = 1, Name = "Account 1" });
		accounts.Add(new Account { Id = 2, Name = "Account 2" });
		accounts.Add(new Account { Id = 3, Name = "Account 3" });

		return Json(accounts, JsonRequestBehavior.AllowGet);
	}

	[HttpGet]
	public JsonResult Index(int id)
	{
		return Json(new Account { Id = id, Name = "Account " + id }, JsonRequestBehavior.AllowGet);
	}

	[HttpPost]
	public JsonResult Index(Account model)
	{
		return Json(model);
	}

	[HttpPut]
	public JsonResult Index(int id, Account model)
	{
		return Json(model);
	}

	[HttpDelete]
	public ActionResult Index(int id)
	{
		return View();
	}
}</pre>
<p>But as mentioned before, the default Index routes doesn&#8217;t work that way. This won&#8217;t even build, since the method signature of <code>Get</code> and <code>Delete</code> are the same.</p>
<h2>Route constraints to the rescure</h2>
<p>Ideally we want our controller to look like the following:</p>
<pre>public class AccountsController : Controller
{
	[HttpGet]
	public JsonResult GetAll()
	{
		List accounts = new List();
		accounts.Add(new Account { Id = 1, Name = "Account 1" });
		accounts.Add(new Account { Id = 2, Name = "Account 2" });
		accounts.Add(new Account { Id = 3, Name = "Account 3" });

		return Json(accounts, JsonRequestBehavior.AllowGet);
	}

	[HttpGet]
	public JsonResult Get(int id)
	{
		return Json(new Account { Id = id, Name = "Account " + id }, JsonRequestBehavior.AllowGet);
	}

	[HttpPost]
	public JsonResult Create(Account model)
	{
		return Json(model);
	}

	[HttpPut]
	public JsonResult Update(int id, Account model)
	{
		return Json(model);
	}

	[HttpDelete]
	public ActionResult Delete(int id)
	{
		return View();
	}
}</pre>
<p>So for this to work, we need to point the individual HTTP verbs to their own action. This can be done by adding an <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.httpmethodconstraint.aspx">HTTP method route constraints</a>, when mapping routes in your <code>RouteConfig</code> (or <code>Global.asax</code>):</p>
<pre>routes.MapRoute("Model_GetAll", "{controller}", new { action = "GetAll" }, new { httpMethod = new HttpMethodConstraint("GET") });
routes.MapRoute("Model_GetOne", "{controller}/{id}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint("GET"), id = @"^\d+$" });
routes.MapRoute("Model_Post", "{controller}", new { action = "Create" }, new { httpMethod = new HttpMethodConstraint("POST") });
routes.MapRoute("Model_Put", "{controller}/{id}", new { action = "Update" }, new { httpMethod = new HttpMethodConstraint("PUT") });
routes.MapRoute("Model_Delete", "{controller}/{id}", new { action = "Delete" }, new { httpMethod = new HttpMethodConstraint("DELETE") });</pre>
<p>Now you can code away in Backbone, and always hit the correct MVC controller actions. If you want to avoid this, upgrade your MVC app to MVC 4 and use <a href="http://stephenwalther.com/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx">Web API controllers</a>. They support this out of the box.</p>
<p>The post <a href="http://martinnormark.com/backbone-js-compatible-routes-aspnet-mvc/">Backbone.js Compatible Routes for, non-Web API, ASP.NET MVC projects</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/backbone-js-compatible-routes-aspnet-mvc/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>How To Hit Back When Your Boss Uses Salary Statistics To Negotiate</title>
		<link>http://martinnormark.com/hit-back-at-salary-statistics/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/hit-back-at-salary-statistics/#comments</comments>
		<pubDate>Thu, 29 Nov 2012 20:18:59 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[Career]]></category>
		<category><![CDATA[career]]></category>
		<category><![CDATA[salary]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=440</guid>
		<description><![CDATA[<p>You sit in a meeting with your boss, negotiating your salary. Of course, you&#8217;re the awesome developer and feel like you should be paid 10x as much as the guy sitting next to you. You know that smart developers who gets things done are scarce, very scarce! And yet, your boss is arguing that your salary should be X because that&#8217;s the average salary for a developer in your area, based on some crappy statistics he pulled off of a website just before the meeting. How To Hit Back With all the confidence you can get, you must counter argue by saying that you are not an average developer. That you think this company needs more than average people to carry out their goals and deliver products that aren&#8217;t average either. And  that he must up his game dramatically, if &#8230; <a href="http://martinnormark.com/hit-back-at-salary-statistics/">Continued</a></p><p>The post <a href="http://martinnormark.com/hit-back-at-salary-statistics/">How To Hit Back When Your Boss Uses Salary Statistics To Negotiate</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>You sit in a meeting with your boss, negotiating your salary.</p>
<p>Of course, you&#8217;re the awesome developer and feel like you should be <a href="http://blogs.construx.com/blogs/stevemcc/archive/2011/01/22/10x-productivity-myths-where-s-the-10x-difference-in-compensation.aspx">paid 10x as much as the guy sitting next to you</a>. You know that smart developers who gets things done are scarce, very scarce!</p>
<p>And yet, your boss is arguing that your salary should be X because that&#8217;s the average salary for a developer in your area, based on some crappy statistics he pulled off of a website just before the meeting.</p>
<h2>How To Hit Back</h2>
<p>With all the confidence you can get, you must counter argue by saying that you are not an average developer. That you think this company needs more than average people to carry out their goals and deliver products that aren&#8217;t average either. And  that he must up his game dramatically, if the negotiations should continue.</p>
<h3>By the way&#8230;</h3>
<p>I have a bunch of invites for <a href="http://careers.stackoverflow.com/">Stack Overflow Careers</a>, so if you&#8217;re interested ping me on <a href="http://twitter.com/martinhn">Twitter</a> and I&#8217;ll invite you.</p>
<p>The post <a href="http://martinnormark.com/hit-back-at-salary-statistics/">How To Hit Back When Your Boss Uses Salary Statistics To Negotiate</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/hit-back-at-salary-statistics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Use Recurly.js with ASP.NET (MVC), C# with this Nu Get library</title>
		<link>http://martinnormark.com/use-recurly-js-with-asp-net-mvc-csharp/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/use-recurly-js-with-asp-net-mvc-csharp/#comments</comments>
		<pubDate>Thu, 01 Nov 2012 20:24:16 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=437</guid>
		<description><![CDATA[<p>Recurly is a full suite recurring payment service that lets you easily create subscription plans, billing cycles, handle customers, revenue etc. They made payment integration dead easy with their awesome JavaScript library called Recurly.js that you can use to inject a payment form onto any page with a simple piece of JavaScript, a long with a server generated signature. But .Net as a platform, and C# as a language is not very well supported by Recurly. They don&#8217;t event provide a client library for creating those signatures. I needed a client library and wrote this simple class that I&#8217;ve now uploaded to Nu Get. The package is called RecurlyJS, and the source code is on GitHub. Enjoy!</p><p>The post <a href="http://martinnormark.com/use-recurly-js-with-asp-net-mvc-csharp/">Use Recurly.js with ASP.NET (MVC), C# with this Nu Get library</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://recurly.com/">Recurly</a> is a full suite recurring payment service that lets you easily create subscription plans, billing cycles, handle customers, revenue etc.</p>
<p>They made payment integration dead easy with their awesome JavaScript library called <a href="http://js.recurly.com/">Recurly.js</a> that you can use to inject a payment form onto any page with a simple piece of JavaScript, a long with a server generated signature.</p>
<p>But .Net as a platform, and C# as a language is not very well supported by Recurly. They don&#8217;t event provide a client library for creating those signatures.</p>
<p>I needed a client library and wrote this simple class that I&#8217;ve now <a href="https://nuget.org/packages/RecurlyJS">uploaded to Nu Get</a>. The package is called RecurlyJS, and the <a href="https://github.com/milkshakesoftware/recurly-js-net">source code is on GitHub</a>.</p>
<p>Enjoy!</p>
<p>The post <a href="http://martinnormark.com/use-recurly-js-with-asp-net-mvc-csharp/">Use Recurly.js with ASP.NET (MVC), C# with this Nu Get library</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/use-recurly-js-with-asp-net-mvc-csharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Unit Testing ASP.NET MVC Controller Action contains specific ActionFilter Attributes</title>
		<link>http://martinnormark.com/unit-testing-asp-net-mvc-controller-action-contains-actionfilter/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/unit-testing-asp-net-mvc-controller-action-contains-actionfilter/#comments</comments>
		<pubDate>Tue, 15 May 2012 21:06:09 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Unit testing]]></category>
		<category><![CDATA[ActionFilters]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=424</guid>
		<description><![CDATA[<p>ActionFilters in ASP.NET MVC are great. You can now easily share logic between controllers without having to inherit from a base controller, that does the common work. I have a content heavy application that supports a set of layouts. Each layout is rendered by setting the Layout view dynamically, which I do from an ActionFilter. My ActionFilter is fully tested, but when you delegate work to an ActionFilter, you should write a test that ensures the filter is defined on the action. Not surprisingly, this is very simple and relies on reflection (Download from Gist: https://gist.github.com/2605628): /// &#60;summary&#62; /// Verifies the controller action, contains an attribute of the specified attributeType. /// &#60;/summary&#62; /// &#60;param name="controller"&#62;The controller.&#60;/param&#62; /// &#60;param name="action"&#62;The action method.&#60;/param&#62; /// &#60;param name="attributeType"&#62;Type of the attribute to look for.&#60;/param&#62; /// &#60;returns&#62;Returns true if the attribute was present on the action. Otherwise &#8230; <a href="http://martinnormark.com/unit-testing-asp-net-mvc-controller-action-contains-actionfilter/">Continued</a></p><p>The post <a href="http://martinnormark.com/unit-testing-asp-net-mvc-controller-action-contains-actionfilter/">Unit Testing ASP.NET MVC Controller Action contains specific ActionFilter Attributes</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/dd410209.aspx">ActionFilters</a> in ASP.NET MVC are great.</p>
<p>You can now easily share logic between controllers without having to inherit from a base controller, that does the common work.</p>
<p>I have a content heavy application that supports a set of layouts. Each layout is rendered by setting the Layout view dynamically, which I do from an ActionFilter. My ActionFilter is fully tested, but when you delegate work to an ActionFilter, you should write a test that ensures the filter is defined on the action.</p>
<p>Not surprisingly, this is very simple and relies on reflection (Download from Gist: <a href="https://gist.github.com/2605628">https://gist.github.com/2605628</a>):</p>
<pre class="prettyprint">/// &lt;summary&gt;
/// Verifies the controller action, contains an attribute of the specified attributeType.
/// &lt;/summary&gt;
/// &lt;param name="controller"&gt;The controller.&lt;/param&gt;
/// &lt;param name="action"&gt;The action method.&lt;/param&gt;
/// &lt;param name="attributeType"&gt;Type of the attribute to look for.&lt;/param&gt;
/// &lt;returns&gt;Returns true if the attribute was present on the action. Otherwise false.&lt;/returns&gt;
public static bool VerifyControllerActionAttribute(this Controller controller, Func&lt;ActionResult&gt; action, Type attributeType)
{
    MethodInfo methodInfo = action.Method;
    object[] attributes = methodInfo.GetCustomAttributes(attributeType, true);
    return attributes.Any(a =&gt; a.GetType() == attributeType);
}</pre>
<p>And the usage looks like this:</p>
<pre class="prettyprint">[TestMethod]
public void Index_ContainsTemplateLayoutAttribute()
{
    HomeController controller = new HomeController();
    bool containsAttribute = controller.VerifyControllerActionAttribute(controller.Index, typeof(TemplateLayoutAttribute));
    Assert.IsTrue(containsAttribute);
}</pre>
<p>Need an introduction? Watch a video about <a href="http://vimeo.com/32617893">unit testing ASP.NET and MVC based web apps</a> on Vimeo, published by Typemock.</p>
<p>The post <a href="http://martinnormark.com/unit-testing-asp-net-mvc-controller-action-contains-actionfilter/">Unit Testing ASP.NET MVC Controller Action contains specific ActionFilter Attributes</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/unit-testing-asp-net-mvc-controller-action-contains-actionfilter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Make features obvious &#8212; forcing usage is even better</title>
		<link>http://martinnormark.com/make-features-obvious-forcing-usage/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/make-features-obvious-forcing-usage/#comments</comments>
		<pubDate>Fri, 11 May 2012 11:20:13 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[feature]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=421</guid>
		<description><![CDATA[<p>When creating software, make your features obvious. A long time ago, Facebook introduced friendlists &#8211; a feature where you can group friends by any name you want. Along comes Google+, and have a feature called circles that, unlike Facebook&#8217;s lists, are very obvious and an integral part of the design and workflow for when adding friends. All over the press, this is the feature they focus on claiming it has an advantage over Facebook. It seems as if they don&#8217;t know about the lists feature of Facebook, which makes it very important to focus on the features you need and make them obvious. People use what they can see, and what they&#8217;re forced to use. It also makes you think about the countless times, when someone says &#8220;I hate the bla bla bla&#8221; &#8211; and most technical minded people just &#8230; <a href="http://martinnormark.com/make-features-obvious-forcing-usage/">Continued</a></p><p>The post <a href="http://martinnormark.com/make-features-obvious-forcing-usage/">Make features obvious &#8212; forcing usage is even better</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>When creating software, make your features obvious.</p>
<div>A long time ago, Facebook introduced friendlists &#8211; a feature where you can group friends by any name you want.</div>
<div></div>
<div>Along comes Google+, and have a feature called circles that, unlike Facebook&#8217;s lists, are very obvious and an integral part of the design and workflow for when adding friends. All over the press, this is the feature they <a href="http://www.huffingtonpost.com/dave-taylor/why-google-plus-circles-facebook_b_888074.html">focus </a>on claiming it has an advantage over Facebook. It seems as if they don&#8217;t know about the lists feature of Facebook, which makes it very important to focus on the features you need and make them obvious.</div>
<div></div>
<div>People use what they can see, and what they&#8217;re forced to use.</div>
<div></div>
<div>It also makes you think about the countless times, when someone says &#8220;I hate the bla bla bla&#8221; &#8211; and most technical minded people just says, &#8220;you can turn it off&#8221;. This is a typical response, but the problem might be that the <strong>defaults are incorrect</strong>.</div>
<p>The post <a href="http://martinnormark.com/make-features-obvious-forcing-usage/">Make features obvious &#8212; forcing usage is even better</a> appeared first on <a href="http://martinnormark.com">Martin Normark&#039;s blog</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/make-features-obvious-forcing-usage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
	</channel>
</rss>
