【问题标题】:Angularjs - dropdown not binding correctly AND not showing initial valueAngularjs - 下拉列表未正确绑定且未显示初始值
【发布时间】:2017-04-02 23:02:52
【问题描述】:

我正在尝试通过调用 AngularJS 中的 WebApi 来获取数据。我已经验证了服务的工作原理,并且我得到了正确的数据。

问题是所选项目未出现,并且结果与模型的绑定似乎不起作用。

就 AngularJS 而言,我是一个相对新手。有人可以告诉我我做错了什么以及如何纠正这些问题吗?

提前致谢!

这里是角码:

var app = angular.module("GreatWestSoftware", [])

app.controller("ContactMeByController",
    function ($scope, $http ,$window) {


        function GetContactByMethods($http) {
            //$scope.Message = 'NULL';
            //$scope.employees = {};
            $http.get('http://localhost:53350/api/ContactBy').then(function (response) {
                $scope.ContactByMethods = response.data;
                $scope.Message = 'OK';
                $scope.gotdata = true;
            },
            function (err) {
                $scope.Message = 'Call failed' + err.status + '  ' + err.statusText;
                $scope.ContactByMethods = {};
                $scope.gotdata = false;
            }
            );

            //window.setTimeout(function () {
            //    $scope.gotdata = true;
            //}, 1000);
        };



        function ShowAlert(msg)
        {
            $window.alert(msg);
        }
    }

);

这是来自 MVC 的模型:

    public class SurveyAnswersHeaderViewModel

{
    public int ProductID { get; set; }

    [Required]
    [Display(Name = "Name:")]
    public string Name { get; set; }


    [EmailAddress]
    [Display(Name = "Your Email Address:")]
    public string Email { get; set; }

    [Phone]
    [Display(Name = "Phone Number:")]
    [DataType(DataType.PhoneNumber,ErrorMessage ="Invalid Phone Number")]
    public string Phone { get; set; }

    [Required]
    [Display(Description ="How should you be contacted",Name ="Contact Me By:",Prompt ="Select contact method")]
    public int ContactBy { get; set; }
}

这是我要加载的页面:

@model GreatWestSoftware.Models.SurveyAnswersHeaderViewModel

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Great West Software Site Survey";
}

@using (Html.BeginForm("Create", "SurveyAnswersHeader", FormMethod.Post))
{
    @Html.AntiForgeryToken()

      <div class="form-horizontal">
            <h4>@ViewBag.SurveyName</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.HiddenFor(m => m.ProductID)
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div ng-app="GreatWestSoftware" ng-controller="ContactMeByController" ng-show="DisplayContactBy">
                    @Html.LabelFor(model => model.ContactBy, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10" >
                        <select id="ContactByDropdown" ng-model="ContactBy" class="form-inline">
                            <option ng-repeat="ContactByoption in ContactByMethods" ng-selected="{{ContactByoption.IsSelected==true}}" value="{{ContactByoption.ContactByID}}">{{ContactByoption.ContactMeBy}}</option>
                        </select>
                        @*@Html.EditorFor(model => model.ContactBy, new { htmlAttributes = new { @class = "form-control" } })*@
                        @Html.ValidationMessageFor(model => model.ContactBy, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
           <div>
               <h4 class="text-danger">@ViewBag.ErrorMessages</h4>
           </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Start Survey" class="btn btn-default" />
                </div>
            </div>
        </div>
}

<div>
    @Html.ActionLink("Skip", "Index","Home")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script src="~/Scripts/GreatWestSoftware.js"></script>
}

我确实得到了下拉列表的值。但奇怪的是,在生成的代码中有一个 。我猜这在列表中显示为空白条目。即使 html 看起来正确,下拉菜单也没有显示所选的初始值。

第二个问题是在提交表单时,选择的值没有绑定到MVC模型。

Here is what appears in the dropdown. The correct data...

Here is the generated html code

【问题讨论】:

    标签: angularjs asp.net-mvc asp.net-web-api


    【解决方案1】:

    下拉菜单未显示初始值,因为该值是在创建选择后初始化的。要解决此问题,您需要在路由解析中加载值。 示例:

    $routeProvider
        .when("/state-name", {
            templateUrl: "your-template.html",
            controller: "ContactMeByController",
            resolve: {
                contactByMethodsPromise: function($http){
                    return $http.get('http://localhost:53350/api/ContactBy');
            }
        }
    })
    

    在你的控制器中:

    app.controller("ContactMeByController",
    function ($scope, $http , $window, contactByMethodsPromise) {
        $scope.ContactByMethods = contactByMethodsPromise;
    }
    

    这应该会修复选择的初始值。

    关于它没有绑定,我不确定 Angular 是否将它绑定到 MVC 模型。它绑定到变量 $scope.ContactBy,然后您可以将其提交到您的 API。

    此外,您应该考虑仅使用 Angular 来呈现您的页面,这不是必需的,并且可能会导致将其与 ASP.NET 混合使用的奇怪行为,如您所见 here

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 1970-01-01
      • 2010-10-06
      • 2014-08-09
      • 2013-12-20
      • 2017-08-25
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      相关资源
      最近更新 更多