Home » Angularjs » Angular ASP.NET MVC Binding

Angular ASP.NET MVC Binding

Posted by: admin January 9, 2018 Leave a comment


In our MVC 5 project we use Angular. The following Razor works nicely:

 @Html.EditorFor(x => x.FirstName,
          new { required = "required", ng_model = "FirstName" })

However, if the MVC Model.FirstName is set to “Bob” when the page is rendered, the Input field is still blank.

If I set this in the Angular controller:

  $scope.FirstName = "@(Model.FirstName)";

Then “Bob” appears.

My question is: Do I have to set the $scope.VARIABLE=MODEL.VARIABLE for every field in the UI, or can I tell Angular to respect what came over from ASP.NET MVC.

Angular is appearing to over write the [input value=”Bob”] that MVC writes.


There is no need to separate the model into individual fields when you bind to scope. Instead you should bind the entire model:

 $scope.model = @Html.Raw(Json.Encode(Model));

This would render to the client as:

 $scope.model = { FirstName: 'John', LastName:'Doe', etc };

Then you can bind your input fields as:

@Html.EditorFor(x => x.FirstName,
      new { required = "required", ng_model = "model.FirstName" })

Personally, I think its cleaner not to use @Html, in favor of simple HTML:

<input ng-model="model.FirstName" required />

In Angular, you don’t really need an id anymore.