Search code examples
angularjsasp.net-mvcasp.net-mvc-4angular-ngmodelangular-services

HTML control not working proper by using angular data-ng-model in ASP.NET MVC


I am using Angular js 1.4.3 and ASP.NET MVC 4.0 with framework 4.0 in Visual Studio 2015 community version.

I have used text control like this in view:

<input id="txtItemId" name="txtItemId" type="text" data-ng-model="ItemEdit.ItemId" value="ItemEdit.ItemId" value="ItemEdit.ItemId" disabled />

I want to get the txtItemId's value set by data-ng-model in Controller side I mean back end side (server side) but I am getting 0 value as output.

My code to get the record is:

FormCollection frm; (defined in function() defination)
string id = Convert.ToInt32(frm["txtItemId"]); // here I get 0 instead of already set value "1"

and second issue is the dropdownlist I have used it to bind the state record using Angular js and done perfectly fine but at the time of Edit angular not set the value as an id in dropdownlist:

<select id="ddlState" name="ddlState" data-ng-options="s.Text for s in stateoptions" data-ng-model="stateselectedOption"></select>

Any help would be appreciated.


Solution

  • This is the expected result as angular will automatically sync form inputs with the current scope - over-writing any values you have set server side.

    You need to initialise the angular scope when the page loads. This can be achieved by converting your MVC model into Json in your view and setting the scope there.

    Angular

    myApp.controller('myController', ['$scope', 'viewModel',
       function ($scope,  viewModel) {
            $scope.viewModel = viewModel;
       }]
    );
    

    View

    <div ng-controller="myController"> ....  </div>
    <script type="text/javascript">
     var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model));
     myApp.value("viewModel", model);
    </script>