Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question
1  
use json for data. – jzm Jun 18 '14 at 0:05
up vote 5 down vote accepted

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.

share|improve this answer
    
That is really great. Perfect. i'll mark it as the answer once SOF lets me. – BahaiResearch.com Jun 18 '14 at 0:16
    
And what to do when your angular code is in a separate *.js file? – lexeme Jun 19 '14 at 12:28
    
<script> app.module('app').value('model', @Html.Raw(Json.Encode(Model)); </script>. The rest of the module definition can be in its own separate file. 'model', can then be injected as needed. – pixelbits Jun 19 '14 at 15:29
    
I could see how this could be used effectively in ASP.NET if there is a real need to fetch the data and serve the initial page in the same request. However, sending two requests may fit better with the angular framework. – pixelbits Jun 19 '14 at 18:35
    
Will your last line of code, in html, be caught by a POST request from mvc? – RageCompex Dec 11 '15 at 23:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.