简体   繁体   English

带有Angular和.net核心的select选项

[英]select option with Angular and .net core

I have angular controller for get and post some data. 我有用于获取和发布一些数据的角度控制器。 I made two controller to work correctly and now when I made 3rd one with mixing two previous controllers get and post doesn't work. 我使两个控制器正常工作,现在当我将第三个控制器与之前的两个控制器混合使用get和post时不起作用。 Could you help to find a problem ? 你能帮忙找到问题吗? Here is a code. 这是代码。 sparePartController.js //sparePartController.js sparePartController.js //sparePartController.js

(function () {

    "use strict";

    angular.module("app")
        .controller("sparePartController", sparePartController);

    function sparePartController($http)
    {
        var vm = this;

        vm.spareParts = [];

        vm.newSparePart = {};

        vm.errorMessage = "";

        vm.isBusy = true;

        $http.get("/spares/getAll")
            .then(function (response) {
                //success
                angular.copy(response.data, vm.spareParts);
            }, function (error) {
                vm.errorMessage = error;
            }).finally(function () {
                vm.isBusy = false;

            });

        vm.addSparePart = function () {

            vm.isBusy = true;

            vm.errorMessage = "";
            $http.post("/spares", vm.newSparePart)
                .then(function (response) {
                    console.log("test");
                    vm.spareParts.push(response.data);
                    vm.newSparePart = {};
                }, function () {
                    console.log = "failed to save new spare";
                    vm.errorMessage = "failed to save new spare";
                }).finally(function () {
                    vm.isBusy = false;

                });

        };
    }
})();

Index.cshtml to show spare parts and add new one Index.cshtml显示零件并添加新零件

@model IEnumerable<RnD.Models.ViewModels.SparePartViewModel>
@{
    ViewBag.Title = "Spare Parts List";
}

@section scripts{
    <script src="~/lib/angular/angular.js"></script>
    <script src="~/js/app.js"></script>
    <script src="~/js/sparePartController.js"></script>
    <script src="~/js/spareTypeController.js"></script>
    <script src="~/js/machineController.js"></script>

}

<div class="row" ng-app="app" ng-controller="sparePartController as vm">
    <!-- Start Modal-->
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
        Create New Spare Part
    </button>
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                </div>
                <div class="modal-body">
                    <form novalidate name="newSpareForm" ng-submit="vm.addSparePart()">
                        <div class="form-group">
                            <label for="InternalCode">Internal Code</label>
                            <input class="form-control" type="text" placeholder="Internal Code" id="InternalCode" ng-model="vm.newSparePart.internalCode" required min="3" />
                        </div>
                        <div class="form-group" ng-controller="machineController as machineVM">
                            <label>Machine Type</label>
                            <select class="form-control" ng-model="machineVM.machineType" ng-options="machine.name for machine in machineVM.machines"></select>
                        </div>
                        <div class="form-group" ng-controller="spareTypeController as spareVM">
                            <label>Spare Type</label>
                            <select class="form-control" ng-model="spareVM.id">
                                <option ng-repeat="spare in spareVM.spares" value="{{spare.id}}">{{spare.name}}</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <input type="submit" value="Add" class="btn btn-success" />
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                </div>
            </div>
        </div>
        <!-- End Modal-->

    </div>
    <hr />
    <div class="panel panel-default" ng-repeat="spare in vm.spareParts">
        <div class="panel-heading">
            {{spare.internalCode}} //it was vm.internalCode
        </div>
        <div class="panel-body">

        </div>
        <div class="panel-footer">

        </div>
    </div>
</div>

PS To add, when I want to post I have problem to catch value from select. 附言:要添加,当我要发布时,我很难从select中获取价值。 Internal code is recognized from angular controller but machinetype it is not recognized that filed always is null. 内部代码可从角度控制器识别,但无法识别机器类型,因此字段总是为空。

here is modelview class 这是modelview类

public class SparePartViewModel
    {
        [Required]
        [StringLength(100)]
        public string InternalCode { get; set; }

        [StringLength(4096)]
        public string Description { get; set; }

        [StringLength(255)]
        public string NameOnFolder { get; set; }

        public decimal? Enter { get; set; }

        public decimal? Exit { get; set; }

        public decimal? Thickness { get; set; }

        public string Band { get; set; }

        public string Color { get; set; }

        public bool Elastic { get; set; }

        [Required]
        public MachineType MachineType { get; set; }

        [Required]
        public virtual SpareType SpareType { get; set; }

    }

I even try in index.cshtml to put this code <select class="form-control" ng-model="vm.newSparePart.machineType" ng-options="machine.name for machine in machineVM.machines"></select> but in this case when I call [From Body] my viewModel is null 我什至尝试在index.cshtml中将以下代码放入<select class="form-control" ng-model="vm.newSparePart.machineType" ng-options="machine.name for machine in machineVM.machines"></select>但在这种情况下,当我调用[From Body]时,我的viewModel为null

Here is my SparePartsController.cs 这是我的SparePartsController.cs

[Route("/spares")]
    [Authorize]
    public class SparePartsController : Controller
    {
        private ILogger<SparePartsController> _logger;
        private ISparePartRepository _repository;

        public SparePartsController(ISparePartRepository repository, ILogger<SparePartsController> logger)
        {
            _logger = logger;
            _repository = repository;
        }

        [HttpGet("")]
        public IActionResult Index()
        {
            return View();
        }

        [HttpGet("getAll")]
        public IActionResult Get()
        {
            try
            {
                var results = _repository.GetAllSpares();

                return Ok(Mapper.Map<IEnumerable<SparePartViewModel>>(results));

            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to get all Spares : {ex}");
                return BadRequest("Error Occurred");
            }
        }

        [HttpPost("")]
        public async Task<IActionResult> Post([FromBody]SparePartViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var newSpare = Mapper.Map<SparePart>(viewModel);

                _repository.AddSpare(newSpare);
                if (await _repository.SaveChangesAsync())
                {
                    return Created($"spare/{newSpare.InternalCode}", Mapper.Map<SparePartViewModel>(newSpare));
                }
            }
            return BadRequest("Failed to save spare.");
        }
    }

I see a few things off here. 我在这里看到一些事情。 1. I don't think /spares is the full URL to the add method. 1.我不认为/ spares是add方法的完整URL。 2. Even if it were, you still need to send it a correct signature - ie the items within the object you send need to match with items in the add spares method signature. 2.即使是,您仍然需要向其发送正确的签名-即,您发送的对象中的项目需要与add spares方法签名中的项目匹配。 3. I don't see where your newSparePart object is getting assigned values; 3.我看不到newSparePart对象在哪里分配值; it's just an empty object. 它只是一个空对象。 Share the method signature for your add spare method so we can verify that the serialized object. 为您的添加备用方法共享方法签名,以便我们可以验证序列化的对象。 Which brings up 4. You likely need to serialize your object to json: JSON.stringify(vm.newSparePart) when you send it via HTTP post. 出现了4.您可能需要通过HTTP发布将对象序列化为json:JSON.stringify(vm.newSparePart)。

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

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