Я пытался заполнить два раскрывающихся списка из моей базы данных. Первый заполняется при загрузке формы, и я хочу заполнить второй после того, как пользователь выберет значение в первом.
Я следовал и адаптировал этот учебник. Но без удачи.
Мой контроллер
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Oracle.ManagedDataAccess.Client;
using MaterialProjectMaterials.Models;
using UserProfile.Models;
using System.Data;
using Microsoft.AspNetCore.Http;
namespace MaterialProject.Controllers
{
public class MaterialsController : Controller
{
private readonly OracleConnection con = new OracleConnection(GetConString.ConString());
public IActionResult Materials()
{
List<Brands> brandslist = new List<Brands>();
brandslist.Insert(0, new Brands { BCodeID = 0, BDescr = "--Select Brand--" });
//Getting Data from Database using EntityFrameworkCore
con.Open();
string b_query = "SELECT codeID, descr FROM itemcategory WHERE codeID LIKE ('3%') AND LENGTH(codeID)= 3 and rownum<=2 ORDER BY descr";
OracleCommand b_cmd = new OracleCommand(b_query, con);
OracleDataAdapter b_da = new OracleDataAdapter(b_cmd);
DataTable b_dt = new DataTable();
b_da.Fill(b_dt);
foreach (DataRow b_rb in b_dt.Rows)
{
brandslist.Add(new Brands
{
BCodeID = Convert.ToInt64(b_rb["codeID"]),
BDescr = b_rb["descr"].ToString()
});
}
con.Close();
ViewBag.BrandsList = brandslist;
return View();
}
[HttpPost]
public IActionResult Materials(Brands objbrand, FormCollection formCollection)
{
//Validation
if (objbrand.BCodeID == 0)
ModelState.AddModelError("", "Select Brand");
else if (objbrand.VCodeID == 0)
ModelState.AddModelError("", "Select Volume");
//Getting selected Value
var BCodeID = HttpContext.Request.Form["BCodeID"].ToString();
var VCodeID = HttpContext.Request.Form["VCodeID"].ToString();
//Setting Data back to ViewBag after Posting Form
List<Brands> brandslist = new List<Brands>();
brandslist.Insert(0, new Brands { BCodeID = 0, BDescr = "--Select Brand--" });
//Getting Data from Database
con.Open();
string b_query = "SELECT codeID, descr FROM itemcategory WHERE codeID LIKE ('3%') AND LENGTH(codeID)= 3 ORDER BY descr";
OracleCommand b_cmd = new OracleCommand(b_query, con);
OracleDataAdapter b_da = new OracleDataAdapter(b_cmd);
DataTable b_dt = new DataTable();
b_da.Fill(b_dt);
foreach (DataRow b_rb in b_dt.Rows)
{
brandslist.Add(new Brands
{
BCodeID = Convert.ToInt64(b_rb["codeID"]),
BDescr = b_rb["descr"].ToString()
});
}
con.Close();
//Assing BCodeID to ViewBag.BrandsList
ViewBag.BrandsList = brandslist;
return View(objbrand);
}
public JsonResult GetVolumes(Int64? BCodeID)
{
if (BCodeID == null)
{
throw new ArgumentNullException(nameof(BCodeID));
}
List<Volume> volumelist = new List<Volume>();
volumelist.Insert(0, new Volume { VCodeID = 0, VDescr = "--Select Volume--" });
//Getting Data from Database
con.Open();
string v_query = "SELECT DISTINCT IG.CODEID, IG.DESCR FROM MATERIAL M INNER JOIN ITEMGROUP IG ON M.IGPID = IG.CODEID INNER JOIN ITEMCATEGORY IC ON '3' || SUBSTR(M.ICTID, 3, 2) = IC.CODEID WHERE M.ICTID LIKE('3%') AND IC.CODEID =" + BCodeID + "ORDER BY CODEID";
OracleCommand v_cmd = new OracleCommand(v_query, con);
OracleDataAdapter v_da = new OracleDataAdapter(v_cmd);
DataTable v_dt = new DataTable();
v_da.Fill(v_dt);
foreach (DataRow v_dr in v_dt.Rows)
{
volumelist.Add(new Volume
{
VCodeID = Convert.ToInt64(v_dr["codeID"]),
VDescr = v_dr["descr"].ToString()
});
}
con.Close();
return Json(new SelectList(volumelist, "VCodeID", "VDescr"));
}
}
}
My View
@model MaterialProjectMaterials.Models.Brands
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var items = "<option value='0'>--Select Volume--</option>";
$("VCodeID").html(items);
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#BCodeID").change(function () {
var url = '@Url.Content("~/")' + "Materials/GetVolumes";
var ddlsource = "#BCodeID";
$.getJSON(url, { BCodeID: $(ddlsource).val() }, function (data) {
var items = '';
$("#VCodeID").empty();
$.each(data, function (i, volume) {
items += "<option value='" + volume.value + "'>" + volume.text + "</option>";
});
$("#VCodeID").html(items);
});
})
})
</script>
<form asp-controller="Materials" asp-action="Materials" method="post" class="form-horizontal" role="form">
<div class="form-group">
<div class="row">
<div class="alert-danger" asp-validation-summary="ModelOnly"></div>
<div class="col-xs-12 col-sm-6 col-lg-4">
<label asp-for="BDescr" class="control-label">Brands</label>
<select asp-for="BCodeID" class="form-control"
asp-items="@(new SelectList(ViewBag.BrandsList, "BCodeID", "BDescr"))"></select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-12 col-sm-6 col-lg-4">
<label class="control-label">Volume</label>
<select class="form-control" id="vCodeID" name="vDescr" asp-for="VCodeID"
asp-items="@(new SelectList(string.Empty, "VCodeID", "VDescr"))"></select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-12 col-sm-6 col-lg-4">
<input id="Submit1" type="submit" value="Submit" />
</div>
</div>
</div>
</form>
}
Мои модели
namespace MaterialProjectMaterials.Models
{
public class MaterialsModel
{
public DbSet<Brands> Brands { get; set; }
public DbSet<Volume> Volume { get; set; }
}
}
namespace MaterialProjectMaterials.Models
{
[Table("ITEMCATEGORY")]
public class Brands
{
[Key]
[Column("CODEID")]
public Int64 BCodeID { get; set; }
[Column("DESCR")]
public string BDescr { get; set; }
[NotMapped]
public Int64 VCodeID { get; set; }
}
}
namespace MaterialProjectMaterials.Models
{
[Table("IT_MATERIAL_VOLUMES")]
public class Volume
{
[Key]
[Column("VCODEID")]
public Int64 VCodeID { get; set; }
[Column("VDESCR")]
public string VDescr { get; set; }
[Column("BDESCR")]
public int BCodeID { get; set; }
}
}
В результате, когда я запускаю проект, я могу получить значения в первом раскрывающемся списке, но когда я выбираю значение, я ничего не возвращаю во второй раскрывающийся список.
Буду признателен за любую помощь.
Заранее спасибо.