11

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.

0

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

6 Comments

That is really great. Perfect. i'll mark it as the answer once SOF lets me.
And what to do when your angular code is in a separate *.js file?
<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.
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.
Will your last line of code, in html, be caught by a POST request from mvc?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.