C# 使用ASP.NET核心MVC编辑级联下拉列表

C# 使用ASP.NET核心MVC编辑级联下拉列表,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我无法根据所选客户的ID从数据库检索/显示CityId值到城市下拉列表,我希望编辑该ID 当我选择要编辑的客户时,它会正确地填充数据库中的数据,城市下拉列表除外。“城市”下拉列表将显示“选择一个城市”以及“州”下拉列表中与该州相关的所有城市 如果我选择了另一个州,那么它会正确加载所选州的所有城市 问题是,它没有显示城市下拉列表的城市值,就像我第一次根据所选客户ID加载页面时所显示的那样 我对jQuery/AJAX非常陌生,有人帮我编写了级联下拉列表的jQuery代码 我在下面提供了我现在使用的V

我无法根据所选客户的ID从数据库检索/显示CityId值到城市下拉列表,我希望编辑该ID

当我选择要编辑的客户时,它会正确地填充数据库中的数据,城市下拉列表除外。“城市”下拉列表将显示“选择一个城市”以及“州”下拉列表中与该州相关的所有城市

如果我选择了另一个州,那么它会正确加载所选州的所有城市

问题是,它没有显示城市下拉列表的城市值,就像我第一次根据所选客户ID加载页面时所显示的那样

我对jQuery/AJAX非常陌生,有人帮我编写了级联下拉列表的jQuery代码

我在下面提供了我现在使用的ViewModel、Controller和Edit视图:

客户模型

public class Customer
{
    public int CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int CityId { get; set; }
    public City City { get; set; }

    public int LocalityId { get; set; }
    public Locality Locality { get; set; }

    public int SubLocalityId { get; set; }
    public SubLocality SubLocality { get; set; }
}
public class City
{
    public int ID { get; set; }
    public string Name { get; set; }

    public List<Customer> Customers { get; set; }
    public List<Locality> Localities { get; set; }
}
public class Locality
{
    public int ID { get; set; }
    public string Name { get; set; }

    public int CityId { get; set; }
    public City City { get; set; }

    public List<Customer> Customers { get; set; }
    public List<SubLocality> SubLocalities { get; set; }
}
public class SubLocality
{
    public int ID { get; set; }
    public string Name { get; set; }

    public int LocalityId { get; set; }
    public Locality Locality { get; set; }

    public List<Customer> Customers { get; set; }
}
城市模式

public class Customer
{
    public int CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int CityId { get; set; }
    public City City { get; set; }

    public int LocalityId { get; set; }
    public Locality Locality { get; set; }

    public int SubLocalityId { get; set; }
    public SubLocality SubLocality { get; set; }
}
public class City
{
    public int ID { get; set; }
    public string Name { get; set; }

    public List<Customer> Customers { get; set; }
    public List<Locality> Localities { get; set; }
}
public class Locality
{
    public int ID { get; set; }
    public string Name { get; set; }

    public int CityId { get; set; }
    public City City { get; set; }

    public List<Customer> Customers { get; set; }
    public List<SubLocality> SubLocalities { get; set; }
}
public class SubLocality
{
    public int ID { get; set; }
    public string Name { get; set; }

    public int LocalityId { get; set; }
    public Locality Locality { get; set; }

    public List<Customer> Customers { get; set; }
}
客户控制器

public class CustomersController : Controller
{
    private readonly WebAppDbContext _context;

    public CustomersController(WebAppDbContext context)
    {
        _context = context;    
    }


    // GET: Customers
    public async Task<IActionResult> Index()
    {
        var webAppDbContext = _context.Customers.Include(c => c.City).Include(c => c.Locality).Include(c => c.SubLocality);
        return View(await webAppDbContext.ToListAsync());
    }


    // GET: Customers/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var customer = await _context.Customers
            .Include(c => c.City)
            .Include(c => c.Locality)
            .Include(c => c.SubLocality)
            .SingleOrDefaultAsync(m => m.CustomerId == id);

        if (customer == null)
        {
            return NotFound();
        }

        return View(customer);
    }


    // GET: Customers/Create
    [HttpGet]
    public ActionResult Create()
    {
        CustomerFormVM model = new CustomerFormVM();
        ConfigureViewModel(model);
        return View(model);
    }


    // POST: Customers/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(CustomerFormVM vm)
    {
        if (ModelState.IsValid)
        {
            var customer = new Customer();
            {
                customer.FirstName = vm.FirstName;
                customer.LastName = vm.LastName;
                customer.CityId = vm.SelectedCity.Value;
                customer.LocalityId = vm.SelectedLocality.Value;
                customer.SubLocalityId = vm.SelectedSubLocality.Value;
            }
            _context.Customers.Add(customer);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }

        else
        {
            ConfigureViewModel(vm);
            return View(vm);
        }
    }


    [HttpGet]
    public JsonResult FetchLocalities(int ID)
    {
        var data = _context.Localities
            .Where(l => l.CityId == ID)
            .Select(l => new { val = l.ID, text = l.Name });
        return Json(data);
    }


    [HttpGet]
    public JsonResult FetchSubLocalities(int ID)
    {
        var data = _context.SubLocalities
            .Where(l => l.LocalityId == ID)
            .Select(l => new { val = l.ID, text = l.Name });
        return Json(data);
    }


    private void ConfigureViewModel(CustomerFormVM model)
    {
        List<City> cities = _context.Cities.ToList();
        model.CityList = new SelectList(cities, "ID", "Name");
        if (model.SelectedCity.HasValue)
        {
            IEnumerable<Locality> localities = _context.Localities.Where(l => l.CityId == model.SelectedCity.Value);
            model.LocalityList = new SelectList(localities, "ID", "Name");
        }
        else
        {
            model.LocalityList = new SelectList(Enumerable.Empty<SelectListItem>());
        }
        if (model.SelectedLocality.HasValue)
        {
            IEnumerable<SubLocality> subLocalities = _context.SubLocalities.Where(l => l.LocalityId == model.SelectedLocality.Value);
            model.SubLocalityList = new SelectList(subLocalities, "ID", "Name");
        }
        else
        {
            model.SubLocalityList = new SelectList(Enumerable.Empty<SelectListItem>());
        }
    }


    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var customervm = new CustomerFormVM();
        {
            Customer customer = _context.Customers.SingleOrDefault(c => c.CustomerId == id);

            if (customer == null)
            {
                return NotFound();
            }

            customervm.CustomerId = customer.CustomerId;
            customervm.FirstName = customer.FirstName;
            customervm.LastName = customer.LastName;
        }
        return View(customervm);
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(CustomerFormVM vmEdit)
    {
        if (ModelState.IsValid)
        {
            Customer customer = _context.Customers.SingleOrDefault(c => c.CustomerId == vmEdit.CustomerId);

            if (customer == null)
            {
                return NotFound();
            }

            customer.FirstName = vmEdit.FirstName;
            customer.LastName = vmEdit.LastName;

            _context.Entry(customer).State = EntityState.Modified;
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(vmEdit);
    }


    // GET: Customers/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var customer = await _context.Customers
            .Include(c => c.City)
            .Include(c => c.Locality)
            .Include(c => c.SubLocality)
            .SingleOrDefaultAsync(m => m.CustomerId == id);
        if (customer == null)
        {
            return NotFound();
        }

        return View(customer);
    }


    // POST: Customers/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var customer = await _context.Customers.SingleOrDefaultAsync(m => m.CustomerId == id);
        _context.Customers.Remove(customer);
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    private bool CustomerExists(int id)
    {
        return _context.Customers.Any(e => e.CustomerId == id);
    }
}
公共类CustomerController:控制器
{
私有只读WebAppDbContext\u context;
公共CustomerController(WebAppDbContext上下文)
{
_上下文=上下文;
}
//获取:客户
公共异步任务索引()
{
var webAppDbContext=_context.Customers.Include(c=>c.City).Include(c=>c.Locality).Include(c=>c.SubLocality);
返回视图(等待webAppDbContext.ToListAsync());
}
//获取:客户/详细信息/5
公共异步任务详细信息(int?id)
{
if(id==null)
{
返回NotFound();
}
var customer=await\u context.Customers
.包括(c=>c.City)
.Include(c=>c.Locality)
.包括(c=>c.次局部性)
.SingleOrDefaultAsync(m=>m.CustomerId==id);
如果(客户==null)
{
返回NotFound();
}
返回视图(客户);
}
//获取:客户/创建
[HttpGet]
公共操作结果创建()
{
CustomerFormVM模型=新的CustomerFormVM();
配置视图模型(模型);
返回视图(模型);
}
//职位:客户/创建
//若要防止套印攻击,请启用要绑定到的特定属性,例如
//更多详细信息请参见http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果创建(CustomPerformVM)
{
if(ModelState.IsValid)
{
var customer=新客户();
{
customer.FirstName=vm.FirstName;
customer.LastName=vm.LastName;
customer.CityId=vm.SelectedCity.Value;
customer.LocalityId=vm.SelectedLocality.Value;
customer.SubLocalityId=vm.SelectedSubLocality.Value;
}
_context.Customers.Add(客户);
_SaveChanges();
返回操作(“索引”);
}
其他的
{
配置视图模型(vm);
返回视图(vm);
}
}
[HttpGet]
公共JsonResult FetchLocalities(int ID)
{
var data=\u context.localies
.Where(l=>l.CityId==ID)
.Select(l=>new{val=l.ID,text=l.Name});
返回Json(数据);
}
[HttpGet]
公共JsonResult获取子局部(int ID)
{
变量数据=_context.sublocalies
.其中(l=>l.LocalityId==ID)
.Select(l=>new{val=l.ID,text=l.Name});
返回Json(数据);
}
私有void配置视图模型(CustomPerformVM模型)
{
列表城市=_context.cities.ToList();
model.CityList=新的选择列表(城市,“ID”,“名称”);
if(model.SelectedCity.HasValue)
{
IEnumerable localities=\u context.localities.Where(l=>l.CityId==model.SelectedCity.Value);
model.LocalityList=新的SelectList(localies,“ID”,“Name”);
}
其他的
{
model.LocalityList=新建SelectList(Enumerable.Empty());
}
if(model.selectedLocation.HasValue)
{
IEnumerable sublocalites=\u context.sublocalites.Where(l=>l.LocalityId==model.SelectedLocality.Value);
model.SubLocalityList=新的选择列表(sublocalites,“ID”,“Name”);
}
其他的
{
model.SubLocalityList=新的SelectList(Enumerable.Empty());
}
}
公共行动结果编辑(int?id)
{
if(id==null)
{
返回NotFound();
}
var customervm=新的CustomerFormVM();
{
Customer=\u context.Customers.SingleOrDefault(c=>c.CustomerId==id);
如果(客户==null)
{
返回NotFound();
}
customervm.CustomerId=customer.CustomerId;
customervm.FirstName=customer.FirstName;
customervm.LastName=customer.LastName;
}
返回视图(customervm);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果编辑(CustomPerformVM vmEdit)
{
if(ModelState.IsValid)
{
Customer=\u context.Customers.SingleOrDefault(c=>c.CustomerId==vmEdit.CustomerId);
如果(客户==null)
{
返回NotFound();
}
customer.FirstName=vmEdit.FirstName;
customer.LastName=vmEdit.LastName;
_context.Entry(customer.State=EntityState.Modified;
_SaveChanges();
返回操作(“索引”);
}
返回视图(vmEdit);
}
//获取:客户/删除/5
公共异步任务删除(int?id)
{
if(id==null)
{
返回NotFound();
}
var customer=await\u context.Customers
.包括(c=>c.City)
.