简体   繁体   English

在POST上使用JQuery创建双精度下拉列表时,SelectList返回0。ASP.Net CORE 2.1

[英]When creating double dropdown SelectList with JQuery on POST returns 0. ASP.Net CORE 2.1

I have created two dropdownlists, of which one acts as a filter for the other. 我创建了两个下拉列表,其中一个充当另一个的过滤器。 So, with dropdown Customer a customer is selected and only a limited set of ClientUsers is presented in in the dropdown ClientUser . 因此,使用下拉菜单Customer会选择一个客户,并且下拉菜单ClientUser中只会显示有限的一组ClientUser I use a Jquery function to make this happen. 我使用Jquery函数来实现这一目标。

The selection works excellent, but when I POST the form the ClientUser is set to 0, instead of the choice. 选择效果很好,但是当我发布表单时,ClientUser设置为0,而不是选择。

在此处输入图片说明

The View is as follows (simplified for readability purposes): 视图如下(为便于阅读而简化):

@model DropDownTester2.Models.CaseViewModel

 <form asp-action="Maak">
     <label asp-for="CaseTitle" class="control-label"></label>
     <input asp-for="CaseTitle" class="form-control" />

     <select id="customerId" asp-for="CustomerId" asp-items='@(new SelectList(ViewBag.customers, "CustomerId", "CompanyName"))'>
          <option>Select Customer Name</option>
      </select>

      <select id="clientUserId" asp-for="ClientUserId" asp-items='@(new SelectList(string.Empty, "ClientUserId", "LastName"))'>
      </select>

      <input type="submit" value="Maak" class="btn btn-default" />
 </form> 

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script type="text/javascript">
        $(function () {
        $("#customerId").change(function () {

            var url = '@Url.Content("~/")' + "Case/getClientUserById";

            var ddlsource = "#customerId";

            $.getJSON(url, { id: $(ddlsource).val() }, function (data) {
            //$.getJSON("@Url.Action("getClientUserById","Case")", { id: $(ddlsource).val() }, function (data) {
                var items = '';
                $("#clientUserId").empty();
                $.each(data, function (i, row) {
                    items += "<option value='" + row.value + "'>" + row.text + "</option>";
                });
                $("#clientUserId").html(items);

            })
        });
    });

    </script>
}

The CaseViewModel is: CaseViewModel为:

public class CaseViewModel
{
    public int CaseId { get; set; }
    public string CaseTitle { get; set; }
    public int CustomerId { get; set; }
    public int ClientUserId { get; set; }

    public IEnumerable<Customer> CustomerList { get; set; }       
    public IEnumerable<ClientUser> ClientUserList {get; set;}

My Model for Case is: 我的Case模型是:

public class Case
{
    public int CaseId { get; set; }
    public string CaseTitle { get; set; }
    public string CaseRoleDescription { get; set; }
    public int CustomerId { get; set; }
    public int ClientUserId { get; set; }

    public virtual Customer Customer { get; set; }        
    public virtual ICollection<ClientUser> ClientUsers { get; set; }

}

Finally my controllers are : 最后,我的控制器是:

// GET: Case/Maak
    public IActionResult Maak()
    {
        ViewBag.customers = _context.Customer.ToList(); 
        return View();
    }

    public JsonResult getClientUserById(int id)
    {
        List<ClientUser> list = new List<ClientUser>();
        list = _context.ClientUser.Where(c => c.Customer.CustomerId == id).ToList();
        list.Insert(0, new ClientUser { ClientUserId = 0, LastName = "Please select a clientuser" });
        return Json(new SelectList(list, "ClientUserId", "LastName"));
    }


    // POST: Case/Maak
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Maak(CaseViewModel model)
    {
        if (ModelState.IsValid)
        {
            var newCase = new Case
            {
                CaseId = model.CaseId,
                CaseTitle = model.CaseTitle,
                CustomerId = model.CustomerId,
                ClientUserId = model.ClientUserId
            };

            _context.Add(newCase);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        ViewData["CustomerId"] = new SelectList(_context.Set<Customer>(), "CustomerId", "CustomerId", model.CustomerId);
        return View(model);
    }

I can't reproduce your issue : 我无法重现您的问题:

在此处输入图片说明

The difference part of codes is that i create the Customer/ClientUser manually but that shouldn't be the issue cause : 代码的不同之处在于我手动创建了Customer / ClientUser,但这不应该成为问题的原因:

    public class Customer {
       public int CustomerId { get; set; }

       public string CompanyName { get; set; }
    }

    public class ClientUser
    {
        public int ClientUserId { get; set; }

        public string LastName { get; set; }
    }

You may search the "ClientUserId " in your pages to confirm whether other function reset the value . 您可以在页面中搜索“ ClientUserId”,以确认其他功能是否重置了该值。

As a workaround, you can also : 作为解决方法,您还可以:

  1. Create a hidden filed in your page and bind to your model property , create the select change event javascript function to set the value based on the selection . 在页面中创建一个隐藏文件并绑定到您的model属性,创建select change event javascript函数以根据选择设置值。
  2. Use Jquery to get the selected opinion , use Ajax to call action function and pass the value as parameter . 使用Jquery获取选定的意见,使用Ajax调用动作函数并将值作为参数传递。

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

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