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' };
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("'", @"\'")) })
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" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With