gpt4 book ai didi

javascript - 如何在下拉列表中选择对象

转载 作者:行者123 更新时间:2023-12-03 11:47:17 25 4
gpt4 key购买 nike

我有城市类(class)

public class City
{
public int Id { get; set; }
public string Name { get; set; }
public string CountryCode { get; set; }
}

和骑行类(class)。

public class Ride
{
public Guid Id { get; set; }
public City From { get; set; }
public List<City> To { get; set; }
public DateTime DateAndTime { get; set; }
}

加载城市、将其传递给 View 、在下拉列表中显示它们并将数据发布回 Controller 的最佳方式是什么?最好的情况是我可以在“To”列中添加多个城市。我找到了Selectize.js但我没有 JavaScript 经验。我可以只传递给选项 JSON 等还是可以是数据库中的城市列表。

感谢您的宝贵时间。

最佳答案

您将需要一个 View 模型,尤其是当您想一次选择多个城市时。例如:

public class RideViewModel
{
public Guid Id { get; set; }
public DateTime DateAndTime { get; set; }

public int FromCityId { get; set; }
public List<int> ToCityIds { get; set; }
public IEnumerable<SelectListItem> CityChoices { get; set; }
}

请注意,没有 List<City> View 模型上的属性。相反,有 ToCityIds它将存储从列表框中选择的 id 值和 CityChoices它将用于填充列表框。您无法发布完整的City列表框中的对象,仅限简单类型,如 int 。因此,在 POST 时,您将使用 ToCityIds 中的值。查找 City来自数据库的实例。您的From也是如此。您实体的属性(property)。

现在,在你的 Controller 中:

private void PopulateCityChoices(RideViewModel model)
{
model.CityChoices = db.Cities.Select(m => new SelectListItem
{
Value = m.Id,
Text = m.Name
});
}

public ActionResult Create()
{
var model = new RideViewModel();
PopulateCityChoices(model);
return View(model);
}

[HttpPost]
public ActionResult Create(RideViewModel model)
{
if (ModelState.IsValid)
{
// Create new `Ride` and map data over from model
var ride = new Ride
{
Id = Guid.NewGuid(),
DateAndTime = model.DateAndTime,
From = db.Cities.Find(model.FromCityId),
To = db.Cities.Where(m => m.ToCityIds.Contains(m.Id))
}
db.Rides.Add(ride);
db.SaveChanges();
}

// Must repopulate `CityChoices` after post if you need to return the form
// view again due to an error.
PopulateCityChoices(model);
return View(model);
}

最后,在您看来,将模型声明更改为:

@model Namespace.To.RideViewModel

然后添加您的 From选择列表和 To列表框:

@Html.DropDownListFor(m => m.FromCityId, Model.CityChoices)

@Html.ListBoxFor(m => m.ToCityIds, Model.CityChoices)

您可以对两者使用相同的选择,因为它们都选择城市。

关于javascript - 如何在下拉列表中选择对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25999501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com