返回子组的jquery方法中返回null

0sgqnhkj  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(366)

我有两种方法从一个表中获取州和城市:
型号:

public string Title { get; set; }

    public long? ParentId { get; set; }

    public bool IsDeleted { get; set; }

    public bool IsActive { get; set; }

这是它的视图模型

public string Title { get; set; }

    public long LocationId { get; set; }

我有两种方法来获取城市和州。使用first,我选择first显示id的第一个城市:

var state = await _packageService.GetStateForUserInfo();
        ViewData["State"] = state;

        var firstLocationId = state.First().LocationId;
        var city = await _packageService.GetCityForUserInfo(firstLocationId);
        ViewData["City"] = city;

从视图模型中删除用户。因为当我使用fromselect列表时,它返回null!
因此,在查看此my select标记之后:

<label class="w-100 d-flex align-items-center" for="">
                            <label> State   </label>

                            <select asp-for="LocationId" asp-items="(@ViewData["State"] as IEnumerable<SelectListItem>)" id="Location_Id" class="form-control">
                                <span asp-validation-for="LocationId"></span>
                                @foreach (var item in ViewBag.state)
                                {
                                    <option value="@item.LocationId">@item.Title</option>

                                }
                            </select>
                            <label> City  </label>
                            <select asp-for="LocationId" asp-items="(@ViewData["city"] as IEnumerable<SelectListItem>)" id="SubLocation_Id" class="form-control ">
                                <span asp-validation-for="LocationId"></span>
                                @foreach (var item in ViewBag.city)
                                {
                                    <option value="@item.LocationId && @item.Title==Title">@item.Title</option>

                                }
                            </select>
                        </label>

这是我的jquery:但它不返回子位置(城市),也不保存id(我的意思是在位置表字段中:parentid==locationid)
@节脚本{

<script>

        $("#Location_Id").change(function() {
            $("#SubLocation_Id").empty();
            $.getJSON("/UserPanel/UserInfo/GetSubGroup/" + $("Location_Id:selected").val(),
                function(data) {
                    $.each(data,
                        function() {
                            $("#SubLocation_Id").append('<option value=' + this.value + '>' + this.text + '</option>');
                        });

                });
        });
    </script>
    }

更新:这是我的获取和发布方法:

[HttpGet("userInfo/first-start-userInfo/{packageId}")]
    public async Task<IActionResult> FirstStartUserInfo(long packageId,UserPanelMenu menu=UserPanelMenu.Packages )
    {
        if (packageId <= 0) return RedirectToAction("NotFound", "Home");
        var userId = User.GetCurrentUserId();
        if (!await _packageService.IsPackagePurchasedByUser(userId, packageId)) return RedirectToAction("NotFound", "Home");

        var state = await _packageService.GetStateForUserInfo();
        ViewData["State"] = state;

        var firstLocationId = state.First().LocationId;
        var city = await _packageService.GetCityForUserInfo(firstLocationId);
        ViewData["City"] = city;

        return View();
    }

    [HttpPost("userInfo/first-start-userInfo/{packageId}")]
    public async Task<IActionResult> FirstStartUserInfo(CreateFirstStartUserInfoViewModel firstStartUserInfo )
    {
        var userId = User.GetCurrentUserId();

        //if (!ModelState.IsValid) return View(firstStartUserInfo);

        var res = await _packageService.CreateFirstStartUserInfoByUser(firstStartUserInfo, userId);

        return View(firstStartUserInfo);
    }

我在服务中填写其属性:。。。。。。

EditFirstStartUserInfoViewModel editFirstStartUserInfo = new EditFirstStartUserInfoViewModel()
                {

                    PackageId = firstStartUserInfo.PackageId,
                    Address = firstStartUserInfo.Address,
                    DayOfBirth = firstStartUserInfo.DayOfBirth,
                    Goal = firstStartUserInfo.Goal,
                    Job = firstStartUserInfo.Job,
                    Marriage = firstStartUserInfo.Marriage,
                    MonthOfBirth = firstStartUserInfo.MonthOfBirth,
                    Sex = firstStartUserInfo.Sex,
                    UserPackageId = userPackageId,
                    UserInfoId = await _packageRepository.GetUserInfoIdByUserPackageIdAndUserInfoSituation(userPackageId, i),
                    YearOfBirth = firstStartUserInfo.YearOfBirth,

                    LocationId = firstStartUserInfo.LocationId == 0 ? null : firstStartUserInfo.LocationId

update2:获取城市的方法:

public async Task<IActionResult> GetSubGroup(long id)
    {
        var city =await _packageService.GetCityForUserInfo(id);
        return Json(city);

    }
0kjbasz6

0kjbasz61#

我在我这边测试了你的代码片段,我担心问题来自 $("Location_Id:selected").val() ,这行代码将带给我 undefined 因此,ajax get请求可能会向服务器发送错误数据。我曾经 $("#Location_Id option:selected").val() 相反
这是我的测试代码——控制器

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            ViewData["State"] = new List<State> {
                new State{ Title="state1_part1",LocationId=1},
                new State{ Title="state1_part2",LocationId=2},
                new State{ Title="state1_part3",LocationId=3},
                new State{ Title="state1_part4",LocationId=4}
            };
            ViewData["City"] = new List<City> {
                new City{ Title="city3",SubLocation_Id=2,LocationId=3},
                new City{ Title="city4",SubLocation_Id=2,LocationId=4}
            };
            return View();
        }

        public JsonResult getCity(string id) {
            if (id == "1")
            {
                var citys = new List<City> {
                    new City{ Title="city1",SubLocation_Id=1,LocationId=1},
                    new City{ Title="city2",SubLocation_Id=1,LocationId=2}
                };
                return Json(citys);
            }
            else {
                var citys = new List<City> {
                    new City{ Title="city5",SubLocation_Id=3,LocationId=5},
                    new City{ Title="city6",SubLocation_Id=3,LocationId=6}
                };
                return Json(citys);
            }

        }

        [HttpPost]
        public IActionResult savedata(HomeModelView hmv) {
            return View();
        }

        [HttpPost]
        public IActionResult savedata2(TestViewModel tmv)
        {
            return View();
        }
    }
}

查看页面:

@model WebApplication1.Models.HomeModelView
@{
    ViewData["Title"] = "Home Page";
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<div>
    <form asp-controller="Home" asp-action="savedata" method="post">
        <label class="w-100 d-flex align-items-center" for="">
            <label> State   </label>

            <select asp-for="@Model.State.LocationId" asp-items="(@ViewData["State"] as IEnumerable<SelectListItem>)" id="Location_Id" class="form-control">
                <span asp-validation-for="@Model.State.LocationId"></span>
                @foreach (var item in ViewBag.state)
                {
                    <option value="@item.LocationId">@item.Title</option>

                }
            </select>
            <label> City  </label>
            <select asp-for="@Model.City.LocationId" asp-items="(@ViewData["city"] as IEnumerable<SelectListItem>)" id="SubLocation_Id" class="form-control ">
                <span asp-validation-for="@Model.City.LocationId"></span>
                @foreach (var item in ViewBag.city)
                {
                    <option value="@item.LocationId && @item.Title==Title">@item.Title</option>

                }
            </select>
        </label>
        <button type="submit">submit</button>
    </form>
    <button id="test">test</button>
</div>

<script>
    $("#Location_Id").change(function () {
        $("#SubLocation_Id").empty();
        console.log($("Location_Id:selected").val());
        var selectedid = $("#Location_Id option:selected").val();
        $.getJSON("https://localhost:44386/home/getCity/" + selectedid,
            function (data) {
                console.log(data[0].title);
                $.each(data,
                    function () {
                        $("#SubLocation_Id").append('<option value=' + this.locationId + '>' + this.title + '</option>');
                    });
        });
    });

    $("#test").click(function () {
        //write the logic to obtain the title and localtion id and send them to the server
        var Title = "test_title";
        var LocationId = 1233;
        $.ajax({
            url: "https://localhost:44386/home/savedata2/",
            type: "POST",
            data: {
                Title: Title,
                LocationId: LocationId
            },
            success: function (data) {
                alert(data);
            }
        });
    });
</script>

视图模型:

namespace WebApplication1.Models
{
    public class TestViewModel
    {
        public string Title { get; set; }
        public long LocationId { get; set; }
    }
}
56lgkhnf

56lgkhnf2#

解决了这个问题。首先,对于jquery,我必须添加选项,正如tiny wang所说的“向城市展示:

$("#Location_Id option:selected").val()

为了解决问题获取城市的locationid,我应该为城市而不是州插入asp:

<label class="w-100 d-flex align-items-center" for="">
                                <label> state </label>

                                <select    id="Location_Id" class="form-control">

                                    @if (state.Any())
                                    {
                                        @foreach (var item in state )
                                        {
                                            <option value="@item.LocationId">@item.Title</option>

                                        }
                                    }
                                </select>
                                <span asp-validation-for="LocationId"></span>

                                <label> City </label>
                                <select asp-for="LocationId" id="SubLocation_Id" class="form-control ">

                                    @foreach (var item in city)
                                    {

                                        <option value="@item.LocationId ">@item.Title</option>

                                    }
                                </select>
                                <span asp-validation-for="LocationId"></span>
                            </label>

相关问题