AngularJS-下拉列表未正确绑定且未显示初始值 [英] Angularjs - dropdown not binding correctly AND not showing initial value

查看:51
本文介绍了AngularJS-下拉列表未正确绑定且未显示初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to get data via a call to a WebApi within AngularJS. I have verified the service works and I am getting the correct data.

问题是所选项目没有出现,并且结果的模型绑定似乎无效.

The problem(s) are that the selected item is not appearing AND the binding to the model for the result does not appear to be working.

就AngularJS而言,我是一个相对较新的人.有人可以告诉我我在做错什么以及如何解决问题吗?

I am a relative newbie in terms of AngularJS. Can somebody please tell me what I am doing wrong and how to correct the issues?

提前谢谢!

这是角度代码:

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似乎正确,该下拉列表也不会显示所选的初始值.

I do get the values of the dropdown. But oddly, in the generated code there is a . I'm guessing that this is showing up as the blank entry in the list. The dropdown is also not showing the selected initial value, even though the html seems correct.

第二个问题是在提交表单时,所选值未绑定到MVC模型.

The second problem is that on the submittal of the form, the selected value is not being bound to the MVC model.

这是下拉菜单中显示的内容.正确的数据...

这是生成的html代码

推荐答案

下拉列表未显示初始值,因为该值是在创建选择之后初始化的.要解决此问题,您需要在路线的解析位置上加载值.示例:

The dropdown is not showing the inital value because the value is being initialiazed after the select is created. To fix this you need to load the values on the resolve of your route. Example:

$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;
}

这应该确定选择的初始值.

This should fix the select initial value.

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

About it not binding, I'm not sure Angular binds it to the MVC Model. It is binding to the variable $scope.ContactBy, which you can then submit to your API.

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

Also, you should consider using only Angular to render your pages, it's not necessary and will probably cause strange behaviours mixing it with ASP.NET, as you can see here.

这篇关于AngularJS-下拉列表未正确绑定且未显示初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆