Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular model binding with MVC Html.TextBoxFOr

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' };
like image 590
Stas Svishov Avatar asked Nov 28 '22 15:11

Stas Svishov


2 Answers

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("'", @"\'"))  })
like image 67
Anthony Chu Avatar answered Dec 11 '22 00:12

Anthony Chu


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" })
like image 32
Alan Avatar answered Dec 11 '22 01:12

Alan