首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ASP.Net Web Api 2 JQuery,传递给getelementbyId()的空字符串;

ASP.Net Web Api 2 JQuery,传递给getelementbyId()的空字符串;
EN

Stack Overflow用户
提问于 2018-02-24 08:21:44
回答 1查看 105关注 0票数 1

我正在开发一个asp.net项目,该项目可以将设备出租给客户。我想把它记录在数据库里。为此,我使用WebApi2控制器和带有AJAX的JQuery。当我尝试点击submit按钮时,没有任何反应。经过检查,在控制台日志中,我得到了将空字符串传递给getelementbyid()的信息;我不确定为什么会发生这种情况。我正在使用Firefox进行测试,这可能很重要。以下是控制器:

代码语言:javascript
运行
复制
(Web API)
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WinterStore.Models;
using WinterStore.Dtos;

namespace WinterStore.Controllers.api
{
    public class NewRentalsController : ApiController
    {
        private ApplicationDbContext _context;
    public NewRentalsController()
    {
        _context = new ApplicationDbContext();
    }

    [HttpPost]
    public IHttpActionResult CreateNewRentals(NewRentalDto newRental)
    {
        var customer = _context.Customers.Single(
            c => c.CustomerId == newRental.CustomerId);

        var equipment = _context.Equipment.Where(
            m => newRental.EquipmentIds.Contains(m.Id)).ToList();

        foreach (var equ in equipment)
        {
            if (equ.NumberAvailable == 0)
                return BadRequest("Equipment is not available.");

            equ.NumberAvailable--;

            var rental = new Rental
            {
                Customer = customer,
                Equipment = equ,
                DateRented = DateTime.Now
            };

            _context.Rentals.Add(rental);
        }

        _context.SaveChanges();

        return Ok();
    }

}
}

(MVC)

代码语言:javascript
运行
复制
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WinterStore.Controllers
{
    public class RentalsController : Controller
    {
        // GET: Rentals
        [AllowAnonymous]
        public ActionResult New()
        {
            return View("AddRental");
        }

        public ActionResult Index()
        {
            return View("AddRental");
        }
    }
}

型号:

代码语言:javascript
运行
复制
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace WinterStore.Models
{
    public class Rental
    {
        public int Id { get; set; }

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

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

        public DateTime DateRented { get; set; }

        public DateTime? DateReturned { get; set; }
    }
}



    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace WinterStore.Models
{
    public class Customer
    {
        public int CustomerId { get; set; }

        [Required]
        [Display(Name ="Name of the customer")]
        [StringLength(255)]
        [MinLength(3, ErrorMessage = "Name must be 3 or more characters long.")]
        public string CustomerName { get; set; }

    }
}

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using WinterStore.Models;

namespace WinterStore.Models
{
    public class Equipment
    {
        [Required]
        public int Id { get; set; }

        [Required]
        [MinLength(2, ErrorMessage = "Name must be 2 characters or more")]
        [Display(Name = "Name of the equipment")]
        public string EquipmentName { get; set; }

        [Display(Name = "Price for 1 hour")]
        public double PriceFor1HourOfRent { get; set; }

        [Required]
        [Display(Name = "Number available in stock")]
        public byte NumberInStock { get; set; }

        public byte NumberAvailable { get; set; }       


        [Display(Name = "Date of rent")]
        public DateTime? DateOfRent { get; set; }

        [Display(Name = "Date of return")]
        public DateTime? DateOfReturn { get; set; }


        public EquipmentType EquipmentType { get; set; }

        [Required]
        [ForeignKey("EquipmentType")]
        public byte EquipmentTypeId { get; set; }







    }
}

DTo:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WinterStore.Dtos
{
    public class NewRentalDto
    {
        public int CustomerId { get; set; }
        public List<int> EquipmentIds { get; set; }

     }
}

查看:

代码语言:javascript
运行
复制
@model dynamic
@{
    ViewBag.Title = "New Rental Form";
}

<div class="container" id="equipmentcontainer">
    <h2>New Rental Form</h2>
    <form id="newRental">
        <div class="form-group">
            <label>Customer</label>
            <div class="tt-container">
                <input id="customer" name="customer" data-rule-validCustomer="true" required type="text" value="" class="form-control" />
            </div>
        </div>

        <div class="form-group">
            <label>Equipment</label>
            <div class="tt-container">
                <input id="equ" name="equ" data-rule-atLeastOneEquipment="true" type="text" value="" class="form-control" />
            </div>
        </div>

        <div class="row">
            <div class="col-md-4 col-sm-4">
                <ul id="equipment" class="list-group"></ul>
            </div>
        </div>

        <button class="btn btn-primary">Submit</button>

    </form>
  </div>

    @section scripts
{
        @Scripts.Render("~/bundles/jqueryval")
        <script>
            $(document).ready(function () {

                var vm = {

                    equipmentIds: []
                };

                var customers = new Bloodhound({
                    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('customerName'),
                    queryTokenizer: Bloodhound.tokenizers.whitespace,
                    remote: {
                        url: '/api/customers?query=%QUERY',
                        wildcard: '%QUERY'
                    }
                });

                $('#customer').typeahead({
                    minLength: 3,
                    highlight: true
                }, {
                    name: 'customers',
                    display: 'customerName',
                    source: customers
                }).on("typeahead:select", function (e, customer) {
                    vm.customerId = customer.Id;
                });

                var equipment = new Bloodhound({
                    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('equipmentName'),
                    queryTokenizer: Bloodhound.tokenizers.whitespace,
                    remote: {
                        url: '/api/equipment?query=%QUERY',
                        wildcard: '%QUERY'
                    }
                });

                $('#equ').typeahead({
                    minLength: 3,
                    highlight: true
                }, {
                    name: 'equipment',
                    display: 'equipmentName',
                    source: equipment
                }).on("typeahead:select", function (e, equipment) {
                    $("#equipment").append("<li class='list-group-item'>" + equipment.equipmentName + "</li>");

                    $("#equ").typeahead("val", "");

                    vm.equipmentIds.push(equipment.id);
                });


                $.validator.addMethod("validCustomer", function () {
                    return vm.customerId && vm.customerId !== 0;
                }, "Please select a valid customer.");

                $.validator.addMethod("atLeastEquipment", function () {
                    return vm.equipmentIds.length > 0;
                }, "Please select at least one equipment.");

                var validator = $("#newRental").validate({
                    submitHandler: function () {
                        $.ajax({
                            url: "/api/newRentals",
                            method: "post",
                            data: vm
                        })
                        .done(function () {
                            toastr.success("Rentals successfully recorded.");

                            $("#customer").typeahead("val", "");
                            $("#equ").typeahead("val", "");
                            $("#equipment").empty();

                            vm = { equipmentIds: [] };

                            validator.resetForm();
                        })
                        .fail(function () {
                            toastr.error("Something unexpected happened.");
                        });

                        return false;
                    }
                });
            });

        </script>
    }

我怀疑,这可能与客户相关的东西有关。验证客户的方法也不能正常工作。(即使选择了客户,也会显示验证消息)。

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-25 01:58:47

这里:

代码语言:javascript
运行
复制
$('#customer').typeahead({
                minLength: 3,
                highlight: true
            }, {
                name: 'customers',
                display: 'customerName',
                source: customers
            }).on("typeahead:select", function (e, customer) {
                vm.customerId = customer.Id;
            });

我应该使用"vm.customerId = customer.customerId;“:P Working now。谢谢穆罕默德·穆罕默德。:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48958021

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档