简体   繁体   中英

DropDownList : Two way data binding with Angularjs in MVC

I am just learning angular js. I want to bind 2-way data binding with Gender Dropdown menu just as like I did with textboxes.

here is sample code for dropdown control code .

<div class="form-group">
    @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.Gender, new List<SelectListItem> {
             //new SelectListItem { Text="Male", Value="M" },
             //new SelectListItem { Text="Female", Value="F" }
             new SelectListItem { }
        }, new { @class = "form-control", @ng_model = "gender", @ng_options="gender" })
    </div>
</div>

 var myapp = angular .module("myModule", []) .controller("mycontroller", function ($scope) { var user = { loginid : "Login ID", fname : "Enter First Name", lname: "Enter Last Name", gender:"Male" }; $scope.user = user; $scope.genders = [ { Value: "M", name: "Male" }, { Value: "F", name: "Female" } ]; }); 

this is my total js file binding. all parts are working fine without dropdown section for gender.

First off I wouldn't suggest doing that in Razor way specially if all of your dropdown values are coming from your angular controller. but to help you out take a look at the code below.

Option 1:

  @Html.DropDownListFor(model => model.Gender, new List<SelectListItem>(), new { @class = "form-control", @ng_model = "gender", @ng_options = "item as item.name for item in genders track by item.value" })

Option 2:

<select name="Gender" ng-options="item as item.name for item in genders track by item.value" ng-model="gender"></select>

Note:

$scope.genders =
[
    { value: "M", name: "Male" },
    { value: "F", name: "Female" }
];
  1. please notice that I changed the "Value" to lowercase in item.value so you might have to change your gender value property to lowercase as well or simply change item.Value to uppercase.
  2. you can use any word aside from "item" to reference to your collection, you can find more of that in the angular document here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM