AngularJS与ASP.NET MVC下拉框选中失效问题求助
Hey there, let's tackle that dropdown selection problem you're facing. I took a look at your code, and there are a couple of key issues causing the selection to fail when you pick an option. Let's break them down and fix them step by step.
What's Going Wrong?
- Incorrect
ng-selectedsyntax: Theng-selecteddirective expects a boolean expression directly, not wrapped in{{}}interpolation. Using interpolation here breaks AngularJS's two-way binding for tracking selections. - Manual selection handling with
ng-repeat: Whileng-repeatcan generate options, AngularJS hasng-optionsspecifically designed for dropdowns—it handles selection state and data binding far more reliably than manually settingng-selected. - Potential type mismatch: If
$scope.ProfileID(from your controller) is a number butst.ProfileIDinProfilelistis a string (or vice versa), AngularJS won't recognize them as a match, even if the values look identical.
Solution 1: Fix Your Existing ng-repeat Code
If you want to stick with ng-repeat, adjust the ng-selected directive and ensure type consistency:
Corrected HTML
<select class="form-control" required name="ProfileID" ng-model="ProfileID"> <option value="">--- Select an option ---</option> <option ng-selected="st.ProfileID == ProfileID" ng-repeat="st in Profilelist" value="{{st.ProfileID}}"> {{st.ProfileName}} </option> </select>
Controller Check
Verify data types match! If responce.data.data[0].ProfileID is a number, confirm each st.ProfileID in Profilelist is also a number (or convert them to the same type using parseInt() or toString()).
Solution 2: Use ng-options (Recommended)
This is AngularJS's best practice for dropdowns—it simplifies binding and eliminates manual selection logic entirely:
Updated HTML
<select class="form-control" required name="ProfileID" ng-model="ProfileID" ng-options="st.ProfileID as st.ProfileName for st in Profilelist"> <option value="">--- Select an option ---</option> </select>
Why This Works Better:
ng-optionsautomatically syncs the selection state with yourng-modelvalue, no need forng-selected.- It maintains proper data type matching between the model and option values.
- It’s cleaner and more efficient than manually generating options with
ng-repeat.
Final Controller Note
Double-check that your controller correctly sets both values after fetching data:
// Assuming 'responce' is your API response $scope.Profilelist = responce.data.data; // Populate dropdown options $scope.ProfileID = responce.data.data[0].ProfileID; // Set initial selection
That should get your dropdown working as expected—when you select an option, the ng-model will update correctly, and the initial selection will display properly too.
内容的提问来源于stack exchange,提问作者Muhammad Rashid

