Binding Razor forms to an AngularJS model with Html.TextBoxFor()

I was hooking up my login page work with angular, but wanted to keep the MVC model authentication (because it works and I like it). So I tried this:

@Html.TextBoxFor(m => m.userName, new { ng-model = “logon.userName” })

Surprisingly this didn’t work, and threw a server 500 error! I worked out that for some reason, Razor doesn’t like the hyphenated attribute name, and I still haven’t figured out why…

I spent ages trying to search for examples where other people had done this, and it took me about 30 minutes before I stumbled upon the explanation, which is this:

If you want to bind your textbox (or other form elements) to your angular model in a Razor view, you need to use the following nomenclature for the angular markup:

@Html.TextBoxFor(m => m.UserName, new { data_ng_model = “logon.userName” })

So there you go! Now there’s one more answer to this odd question out there, and you might only have to spend 28 minutes searching for the answer! 🙂

(Update: the hyphen is an invalid character for C# properties. Underscores should be used, which are rendered as hyphens! Thanks Simmo for clearing that one up!)

Tagged with: , , , , ,