Sukesh Chand
Sukesh Chand

Reputation: 3047

How to Link MVC Model data with Angular JS Model

I am using MVC Razor View with AngularJS.

I am creating the UserMaster object in controller and passing to the view

Function AddNewUser() As ActionResult
       Dim objUser As New UserMaster()
        Return View("UserMaster", objUserMaster)
End Function

In View, By using HTML helper classes the text box and validation controls will be created

@<div ng-app ng-controller="UserController">
    @Html.EditorFor(Function(model) model.UserName)
    @Html.ValidationMessageFor(Function(model) model.UserName)

In the client side using the following statement the AngularJS model is created

    <script type="text/javascript">
           function UserController($scope, $http) {
           $scope.UserData = @Html.Raw(Json.Encode(Model));
           }
    </script>

The server side validations(which I have written in the UserMaster Class) are working fine in client side, The razor engine is automatically doing that by generating client side validation scripts.

I am automatically getting flourished model in server side after submit.

But I am not able to manipulate/get the model data in client side using AngularJS (by using $scope.UserData.UserName). I want to access the UserName value inside the text box when the user is modifying it by using angular JS.. How?

Upvotes: 1

Views: 1751

Answers (1)

Sukesh Chand
Sukesh Chand

Reputation: 3047

It can be possible by using htmlAttributes in MVC - 5

@Html.EditorFor(Function(model) model.UserName, New With {Key .htmlAttributes = New With {Key .ng_model = "model.UserName"}})

we have to use ng_model insted of ng-model and MVC will render as ng-model in runtime

Upvotes: 2

Related Questions