Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ASP.NET MVC Binding

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.

like image 668
Ian Vink Avatar asked Jun 17 '14 23:06

Ian Vink


1 Answers

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.

like image 153
pixelbits Avatar answered Oct 18 '22 07:10

pixelbits