4

I have controls that are model tied to ASP.net MVC5

 @Html.TextBoxFor(model => model.OriginLocation.City, new { @class = "form-control", data_ng_model = "address1.City", test_change = "" })

So when the page loads the value of text box input is bound and should display value coming from service with Razor bound controls, latter i can manipulate that value which changes angular model for this control. What i have is textbox loads empty. I can see the value when I view source but its not displayed.

<input class="form-control ng-pristine ng-valid" data-ng-model="address1.City" data-val="true" data-val-length="The field City must be a string with a maximum length of 50." data-val-length-max="50" id="OriginLocation_City" name="OriginLocation.City" test-change="" type="text" value="Manheim">

js fragment

app.controller('LocationCtrl', ["$scope",
function ($scope) {
  $scope.address1 = { Label: 'address1' };
3
  • can you also show your script? Jul 21, 2014 at 5:37
  • .js? I did not set anything in js, but now tried getting value of controls w jquery, which is not prefered but still nothing here's the fragment app.controller('LocationCtrl', ["$scope", function ($scope) { $scope.address1 = { Label: 'address1', Address1: $("#OriginLocation.Address1").val(), City: $("#OriginLocation.City").val(), State: $("#OriginLocation.State").val(), PostalCode: $("#OriginLocation.PostalCode").val(), }; Jul 21, 2014 at 5:43
  • I mean can you show your js in your post, not in a comment. There's not enough information in the original post for anyone to give any kind of an answer. Jul 21, 2014 at 5:56

4 Answers 4

19

ngModel has precedence over the value that is originally set (it's setting the value to "" because the model doesn't exist). Take a look here...

http://jsfiddle.net/yApeP/

But you can specify a value using ngInit...

http://jsfiddle.net/D7vh7/

Which means you can use ngInit when generating the textbox...

@Html.TextBoxFor(model => model.OriginLocation.City,
    new { @class = "form-control", 
         data_ng_model = "address1.City", 
         test_change = "",
         data_ng_init = string.Format("address1.City = '{0}'", Model.OriginLocation.City.Replace("'", @"\'"))  })
5
  • I tried with ng_init and it does work, but is that the best and the only way to do it? Jul 21, 2014 at 12:30
  • IMHO this is far from ideal. What are you trying to do with Angular? Personally, I would either stick to using MVC/Razor with a bit of jQuery, or have Angular render the page and fetch/save data via services. Jul 21, 2014 at 16:33
  • 1
    what im trying to do is load data from server so render with MVC/Razor, but latter when there are interactions on the form use angular for 2 way data binding, for example type ahead for address, other things like modifying value of 1 control changes values of others. Jul 21, 2014 at 21:23
  • And when it's time to submit the form, it's via a form post to the MVC controller? Jul 21, 2014 at 21:25
  • I can't think of much better ways to do this. There's a lot of friction in this design, as you have to do a lot of work to get the data from MVC to Angular. You can look at this answer to see how to can place your C# model in the JavaScript as JSON, I don't know if it'd be any better... stackoverflow.com/a/23274892/3199781 ... I think if you're going to be doing more in Angular such as adding autocomplete, you'd be writing REST services anyway to support those. You might as well convert the whole thing to a SPA with REST APIs. Jul 21, 2014 at 21:37
2

Angular will replace the contents of the text box with the value from its own model, which means you need to populate the Angular model. This can be achieved quickly by serializing your MVC model (or part of it) into your Angular model:

app.controller("TestController", function($scope) {
    $scope.person = @Html.Raw(JsonConvert.SerializeObject(Model.Person));
});

You can then render your MVC controls in the view like this:

@Html.TextBoxFor(x => x.Person.Name, new { ng_model = "person.Name" })
4
  • 1
    If you use the @Html.Raw() method to populate your model, you need to extract the code of your controller from your .js file and put it directly inside your page template which is kind of a bad pattern to follow since all your JS should all be at the same place and not dispatch all over your solution.
    – RPDeshaies
    Feb 6, 2015 at 14:19
  • Yes, I agree completely. I came to the conclusion (with more experience) that mashing together two separate MVC frameworks just doesn't work well. Angular over WebAPI works great, and is a much better solution to this.
    – Alan
    Feb 6, 2015 at 14:36
  • I really love Angular, but I don't understand why this framework has to prioritize the content of the model value instead of getting it's value from the input. This is not really a two-way binding framework if it does not get the value of the HTML when loading the page or at least give us the ability to setup a config in our controller to do so. Just my humble opinion. Do you use something different than Angular to do that sort of process now ?
    – RPDeshaies
    Feb 6, 2015 at 15:44
  • No, I tend to use Angular with static HTML templates, and pull data down using WebAPI service calls. I don't think there is an elegant way to make Angular preload its scope with data from the input fields.
    – Alan
    Feb 6, 2015 at 15:48
2

Considering the answer by @Alan, I found a way that is "kind of" clean. Well that is the solution that I am using when creating ASP MVC Projects with Angular.js.

Instead of serializing the model inside the Angular controller (which would require to declare the controller inside of the Razor template), I serialize it in a global variable in each of my razor template like :

<script>
    //Add the namespace you want to not poluate the global namespace
    window.Model = @Html.Raw(JsonConvert.SerializeObject(Model))
</script>

I also use the property attribute [ScriptIgnore] for the properties I don't want to serialize (that could cause circular references).

public class Classroom {
    public string Title {get;set;}

    [ScriptIgnore]
    //Students could be associated to classroom, and that classroom has  
    //  students etc. If you want those properties, create a new object in a 
    //  PageView withtout circular references
    public List<Students> Students {get;set;}
}

After that, inside of my controllers, I simply do something like

app.controller("TestController", function($scope) {
    $scope.model = window.Model;
    //My other stuff...
});

Also, that way your angular Model always have the SAME properties has your ASP MVC Model.

0

One clean way to solve this life-cycle issue is by writing a directive for the "value" attribute for the input.

At first you can simply write the Razor's model value in yout input element by using the basic Razor syntax.

 <input type="text" class="form-control" id="name" name="name" value="@Model.Name" data-ng-model="myModel.name">

That will write the value of the @Model.Name in the input when the page is rendered, but this value will be replaced by empty values when Angular starts the bindings.

So you can write a directive, and on the "link" method you can play with the ngModel in order to keep the value that was present in the input before Angular cleans it. (The property 'prioriy: 0' indicates that the directive should be compiled as soon as possible)

function inputDirective(){
    return {
        restrict:'A',
        priority: 0,
        require: 'ngModel',
        link: function(scope, elem, attrs, ngModelCtrl){                      
                  ngModelCtrl.$setViewValue($(elem).val());
              }
    };
}

That should restore the value written by Razor in your Angular's model

Your Answer

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

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