AngularJs and ASP.NET MVC 5 - ng-model overriding

2019-04-28 17:12发布

问题:

I have a form built using ASP.NET MVC 5 using @Html.TextBoxFor to populate the form with my model (e.g, after a form navigation or server side validation failure).

I have now introduced a client side address lookup using Angular which means some of the form fields are now decorated with ng-model to enable the Angular lookup to populate the searched address.

e.g.:

@Html.TextBoxFor(m => m.Town, new { @class="form-control", ng_model="address.town" })

Adding the ng-model now overrides the value set from the MVC model when the page is reloaded.

Viewing the source in the browser shows that the textbox value is set correctly to Town from the MVC model but Angular then comes along and populates it with address.town which is empty so the form displays no value.

How can I prevent Angular from doing this?

回答1:

You can use ng-init to force a value from MVC

<input name="Town" type="text" ng-model="address.town" ng-init="address.town= @Model.Town" />

@Html.TextBoxFor(m => m.Town, new { ng_model="address.town", ng_init="address.town= Model.Town" })

Alternatively, I use a directive which I found here https://stackoverflow.com/a/22567485/2030565

app.directive('input', function ($parse) {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, element, attrs) {
            if (attrs.ngModel) {
                val = attrs.value || element.text();
                $parse(attrs.ngModel).assign(scope, val);
            }
        }
}; });


回答2:

You could set a variable in a Javascript section at the bottom of the server template that your Angular controller assigns to the model on initialization.

<script>
     My.Namespace.town = @Html.Raw(Model.Town);
</script>