How to Set AngularJs Controller Properties from MVC4 ActionResult
-
20-12-2019 - |
Frage
I have an MVC5 Controller that loads and object and sends it to a View for editing. The Edit form view has a dropdown control containing US States which is bound to an AngularJS Controller property called containing an array of states.
I want set the AngularJS property $scope.SelectedState from the View Model so that the dropdown displays the correct state. I cannot find a way to pass the MVC Model State Value cleanly to the AngularJS Controller Property. Thanks
$scope.SelectedState= {{I want to set this value from the MVC Model}};
HTML Below
<label for="States" class="control-label col-md-2">States</label>
<div class="controls col-md-4">
<select ng-model="SelectedState" id="States" class="form-control" ng-options="st.abbreviation + ' - ' + st.name for st in States.USStates track by st.abbreviation">
<option value="">-- Choose State --</option>
</select>
<input type="hidden" id="SelectedState" name="SelectedState" value="{{SelectedState}}" />
</div>
Here is a Plunker demo of the solution:
Lösung
<label for="States" class="control-label col-md-2">States</label>
//convert your Model.State to Json and set States using ng-init
<div class="controls col-md-4" ng-init="States = @Html.Raw(Json.Encode(Model.State))">
<select ng-init=n g-model="SelectedState" id="States" class="form-control" ng-options="st.abbreviation + ' - ' + st.name for st in States.USStates track by st.abbreviation">
<option value="">-- Choose State --</option>
</select>
<input type="hidden" id="SelectedState" name="SelectedState" value="{{SelectedState}}" />
</div>
Andere Tipps
In the html: <div ng-init="SelectedState = @(Model.SelectedState)"></div>
Replace @(Model.SelectedState)
with whatever from your MVC model. My example is in Razor.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow