简体   繁体   English

DropDownList:在MVC中使用Angularjs进行双向数据绑定

[英]DropDownList : Two way data binding with Angularjs in MVC

I am just learning angular js. 我只是在学习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. 这是我的总js文件绑定。 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. 首先,如果您所有下拉值均来自角度控制器,我不建议您特别以Razor方式进行操作。 but to help you out take a look at the code below. 但是为了帮助您查看下面的代码。

Option 1: 选项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: 选项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. 请注意,我在item.value中将“值”更改为小写,因此您可能必须将性别值属性也更改为小写,或者将item.Value更改为大写。
  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. 您可以使用除“项目”之外的任何词来引用您的收藏,您可以在此处的角度文档中找到更多的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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