'How do you get the parent drop-down list to child selection, instead of showing all the children selection in the second drop-down?
It's been a great experience learning ASP.NET MVC Razor.
I have a web grid in Razor and I have two drop-down list boxes that filters the web grid data on the web grid at the top, which works fine. I have two other drop-down list boxes that shows up in the row and I want to filter the row "Location" list box based on the row "Section" list box without populating the web grid.
I just want to filter the values in the "row location drop-down list box, based on the row section drop-down list box, without populating the web grid, but capturing the values to move the row data to another row based on what I select in the two list boxes on that row"... is what I am trying to do and I am not sure about how to do this
Any help would be greatly appreciated!
ASP.NET MVC Razor web grid:
<hr />
<div id="content">
@webGrid.GetHtml(tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
displayHeader: true,
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
htmlAttributes: new { @id = "webGrid", @class = "Grid" },
columns: webGrid.Columns(
webGrid.Column(header: "Actions", format:@<span class="link">
<!--Add Checkbox here-->
<!-- Note: We can add clickable rows as an option for user. -->
@Html.CheckBoxFor(model => model.SelectedMoveIsChecked, new { @Class = "SelectedMoveIsChecked", @id = "SelectedMoveIsChecked" })
<!-- Html.CheckBox("isActive", false, item.isSelectdRow, true, new { id = "CheckBoxSelectedBeginMove", Class = "CheckBoxIsSelected" })
Html.CheckBoxFor(Model.Input_Location, item.isSelectdRow, new { = "'SelectedRows'", data_val = item.Location }) -->
<a class="Edit" href="javascript:;">Edit</a>
<a class="Clear" href="javascript:;">Clear</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
</span>),
webGrid.Column(header: "LocationID", format: @<span
class="label"><a>@item.LocationID</a></span>, style:
"LocationID"),
webGrid.Column(header: "UserName", format: @<span
class="label"><a>@item.UserName</a></span>, style: "UserName"),
webGrid.Column(header: "Location", format: @<span>
@Html.DropDownListFor(model => model.LocationList,
Model.LocationList, "Location", new { IReadOnlyDictionary = "document.forms[0].submit();", @id = "RowLocationDropDownList",
@class = "RowLocationDropDownList", @visibility = "hidden", @placeholder = "Location" })
<input id="Location" class="inputEditData" type="text"
value="@item.Location" style="display:none"
placeholder="Location" />
<span class="label"><a>@item.Location</a></span>
</span>, style: "Location"),
webGrid.Column(header: "Section", format: @<span>
<optqroup>
@Html.DropDownListFor(modelList => modelList.SectionList,
Model.SectionList, "Section", new { IReadOnlyDictionary =
"document.forms[0].submit();", @id = "RowSectionDropDownList",
@class = "RowSectionDropDownList", @visibility = "hidden",
@placeholder = "Section" })
<input id="Section" class="inputEditData" type="text"
value="@item.Section" style="display:none" placeholder="Section" />
<span class="label"><a>@item.Section</a></span>
</span>, style: "Section"),
webGrid.Column(header: "TrailerNumber", format: @<span>
<span class="label"><a>@item.TrailerNumber</a></span>
<input id="TrailerNumber" class="inputEditData" type="text"
value="@item.TrailerNumber" style="display:none"
placeholder="TrailerNumber" />
</span>, style: "TrailerNumber"),
webGrid.Column(header: "CarrierName", format: @<span>
<span class="label"><a>@item.CarrierName</a></span>
<input id="CarrierName" class="inputEditData" type="text"
value="@item.CarrierName" style="display:none"
placeholder="CarrierName" />
</span>, style: "CarrierName"),
webGrid.Column(header: "LoadCommodityStatus", format: @<span>
<span class="label"><a>@item.LoadCommodityStatus</a></span>
<input id="LoadCommodityStatus" class="inputEditData" type="text"
value="@item.LoadCommodityStatus" style="display:none"
placeholder="LoadCommodityStatus" />
</span>, style: "LoadCommodityStatus"),
webGrid.Column(header: "DateLoaded", format:
@<span class="label"><a>@item.DateLoaded</a></span>, style:
"DateLoaded"),
webGrid.Column(header: "PlantLocation", format: @<span>
<span class="label"><a>@item.PlantLocation</a></span>
<input id="PlantLocation" class="inputEditData" type="text"
value="@item.PlantLocation" style="display:none"
placeholder="PlantLocation" />
</span>, style: "PlantLocation")))
</div>
<div id="RowCountBpttom"><b>Records: @firstRecord -
@lastRecord of @webGrid.TotalRowCount</b></div>
</div>
<br /><br />
<div class="WebGridTable">
</div>
@if (webGrid.HasSelection)
{
//SelectedMoveIsChecked
//Get the values:
//var LocationID =
webGrid.SelectedRow.Value.LocationID; //Note: ID is autogenerated.
var Location = webGrid.SelectedRow.Value.Location;
var Section = webGrid.SelectedRow.Value.Section;
var TrailerNumber =
webGrid.SelectedRow.Value.TrailerNumber;
var CarrierName =
webGrid.SelectedRow.Value.CarrierName;
var LoadCommodityStatus =
webGrid.SelectedRow.Value.LoadCommodityStatus;
var DateLoaded =
webGrid.SelectedRow.Value.DateLoaded;
var PlantLocation =
webGrid.SelectedRow.Value.PlantLocation;
int SelectedMovesCount = webGrid.SelectedRow.Count()
+ 1; //Add Selected Move once confirmed.
//logic
}
</form>
</div>
Controller:
public class HomeController : Controller
{
// input NewRow_Location.
public string Input_Location;
public string Input_Section;
public string Input_TrailerNumber;
public string Input_CarrierName;
public string Input_CommodityStatus;
public string Input_PlantLocation;
public WebGrid webGrid { get; set; }
public object LocationDatas { get; set; }
public object LocationID { get; set; }
public string Location { get; set; }
public string TrailerNumber { get; set; }
public string CarrierName { get; set; }
public string UserName { get; set; }
// GET: Home
public ActionResult Index()
{
// Note: In the controller we can specify the PlantLocation default.
YardDogModel model = PopulateModel("102 - Fort Worth, TX", null, null, null);
return View(model);
}
// Controls DropDownList PlantLocation/Section Selection.
[HttpPost]
public ActionResult Index(string plantLocation, string section, string sectionList, string locationList)
{
// If (EmployeeNumber == 3921) //Restricts to only that PlantLocation.
plantLocation = "102 - Fort Worth, TX";
YardDogModel model = PopulateModel(plantLocation, section, sectionList, locationList);
return View(model);
}
// Population Controller. References list selection.
public static YardDogModel PopulateModel(string country, string city, string cityList, string townList)
{
using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
{
YardDogModel model = new YardDogModel()
{
LocationDatas = (from c in entities.LocationDatas
where c.PlantLocation == country && c.Section == city && c.Section == c.Section && c.Location == c.Location && c.PlantLocation == country || string.IsNullOrEmpty(country) || string.IsNullOrEmpty(city) && c.PlantLocation == country
select c).ToList(),
SectionList = (from c in entities.LocationDatas
where !string.IsNullOrEmpty(c.Section) && c.Section != null && country == c.PlantLocation
select new SelectListItem { Text = c.Section, Value = c.Section }).Distinct().ToList(),
LocationList = (from c in entities.LocationDatas
where !string.IsNullOrEmpty(c.Location) && c.Location != null // && country == c.PlantLocation// && townList == c.Location // && city == c.Section && country == c.PlantLocation
select new SelectListItem { Text = c.Location, Value = c.Location }).Distinct().ToList(),
Section = (from c in entities.LocationDatas
where !string.IsNullOrEmpty(c.Section) && c.Section != null && country == c.PlantLocation
select new SelectListItem { Text = c.Section, Value = c.Section }).Distinct().ToList(),
PlantLocation = (from c in entities.LocationDatas
where (c.PlantLocation == c.PlantLocation)
select new SelectListItem { Text = c.PlantLocation, Value = c.PlantLocation }).Distinct().ToList(),
};
return model;
}
}
[HttpPost]
public ActionResult UpdateCustomer(LocationData customer)
{
using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
{
LocationData updatedCustomer = (from c in entities.LocationDatas
where c.LocationID == customer.LocationID
select c).FirstOrDefault();
// Check for Duplicates.
FindDuplicates(customer);
// HighlightDuplicate(webGrid);
// x => customer.TrailerNumber == x.TrailerNumber && x.TrailerNumber == customer.TrailerNumber // erases all data except the first cell TrailerNumber.
if (customer.TrailerNumber != null)
updatedCustomer.TrailerNumber = customer.TrailerNumber.ToUpper();
else
updatedCustomer.TrailerNumber = customer.TrailerNumber = null;
if (customer.CarrierName != null)
updatedCustomer.CarrierName = customer.CarrierName.ToUpper();
else
updatedCustomer.CarrierName = customer.CarrierName = null;
if (customer.LoadCommodityStatus != null)
updatedCustomer.LoadCommodityStatus = customer.LoadCommodityStatus.ToUpper();
else
updatedCustomer.LoadCommodityStatus = customer.LoadCommodityStatus = null;
// Create today's Date for a timestamp of inputs.
DateTime now = DateTime.Today;
customer.DateLoaded = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
updatedCustomer.DateLoaded = customer.DateLoaded;
entities.SaveChanges();
// Refresh(out, customer.ToString());
}
return new EmptyResult();
}
// Argument for when a Check Box is first Selected in the populated web grid.
[HttpPost]
public ActionResult SelectedMoveIsChecked()
{
//Color.Red.();
return new EmptyResult();
}
//Refresh the Form on Data changes.
/*
public void Refresh(WebBrowserRefreshOption opt, string customer)
{
PopulateModel(opt.ToString(), customer);
}
*/
// Clear the three columns in the Web Grid.
[HttpPost]
public ActionResult ClearCustomer(LocationData clear)
{
using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
{
LocationData updatedCustomer = (from c in entities.LocationDatas
where c.LocationID == clear.LocationID
select c).FirstOrDefault();
if (clear.TrailerNumber != null)
updatedCustomer.TrailerNumber = null;
else
updatedCustomer.TrailerNumber = clear.TrailerNumber = null;
if (clear.CarrierName != null)
updatedCustomer.CarrierName = null;
else
updatedCustomer.CarrierName = clear.CarrierName = null;
if (clear.LoadCommodityStatus != null)
updatedCustomer.LoadCommodityStatus = null;
else
updatedCustomer.LoadCommodityStatus = clear.LoadCommodityStatus = null;
entities.SaveChanges();
}
return new EmptyResult();
}
// Alert for Duplicate TrailerNumber.
private string FindDuplicates(LocationData customer)
{
using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
{
var query = customer.TrailerNumber.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => y.Key).ToList();
//query.foreach(z => Console.WriteLine("{0} -> {1} {2}", z.TrialerNumber, z.Name, z.Surname)).ToList();
foreach (var item in query)
//while (customer.TrailerNumber.Count() > 1 || DialogResult.No.Equals(true) && customer.TrailerNumber.Count() == 1)
{
//Mark the Duplicate to show in MSG Box.
string Duplicate = '*' + customer.TrailerNumber;
string CarrierName = customer.CarrierName;
if (MessageBox.Show("Duplicate Trailer Number Found! Keep Entry?", Duplicate, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ //using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
WebGrid webGridDuplicates = new WebGrid();
LocationData ListDuplicates = new LocationData();
//string x=ListDuplicates.TrailerNumber;
//Mark the duplicate.
customer.TrailerNumber = '*' + customer.TrailerNumber;
//entities.LocationDatas.ForEach(x => Console.WriteLine("{0} -> {1} {2}", x.TrailerNumber, x.CarrierName));
entities.SaveChanges();
}//User chooses No.
else if (MessageBox.Show("Duplicate Trailer Number Found! Keep Entry?", Duplicate, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
customer.TrailerNumber = customer.TrailerNumber = null;
customer.CarrierName = customer.CarrierName = null;
customer.LoadCommodityStatus = customer.LoadCommodityStatus = null;
entities.SaveChanges();
//Refresh the form using a meta tag.
///Response.AppendHeader("Refresh", "5");
}
else //Did not find a duplicate in TrailerNumber.
{
//Do Nothing.
}
}
return customer.TrailerNumber;
}
}
public static void HighlightDuplicate(WebGrid webGrid)
{
for (int currentRow = 0; currentRow < webGrid.Rows.Count - 1; currentRow++)
{
WebGridRow rcompare = webGrid.Rows[currentRow];
for (int otherRow = currentRow + 1; otherRow < webGrid.Rows.Count; otherRow++)
{
WebGridRow row = webGrid.Rows[otherRow];
bool duplicateRow = true;
if (!rcompare.Value["TrailerNumber"].Value.Equals(row.Value["TrailerNumber"].Value))
{
duplicateRow = false;
break;
}
if (duplicateRow)
{
rcompare.Value.DefaultCellStyle.BackColor = Color.Green;
rcompare.Value.DefaultCellStyle.ForeColor = Color.White;
row.Value.DefaultCellStyle.BackColor = Color.Green;
row.Value.DefaultCellStyle.ForeColor = Color.Yellow;
}
}
}
}
public ActionResult YardDogWebGridAdmin(ContYardDogAdmin ContYardDogData)
{
//Note: If you had a master page, then you would do like this.
//string Location = Request.Form["ctl00$cpd_Main$Input_Location"];
string Input_Location = Request.Form["Input_Location"];
string Input_Section = Request.Form["Input_Section"];
string Input_TrailerNumber = Request.Form["Input_TrailerNumber"];
string Input_CarrierName = Request.Form["Input_CarrierName"];
string Input_LoadCommodityStatus = Request.Form["Input_LoadCommodityStatus"];
string Input_PlantLocation = Request.Form["Input_PlantLocation"];
//ContYardDogAdmin ContYardDogData = new ContYardDogAdmin();
ContYardDogData.Location = Input_Location;
ContYardDogData.Section = Input_Section;
ContYardDogData.TrailerNumber = Input_TrailerNumber;
ContYardDogData.CarrierName = Input_CarrierName;
ContYardDogData.LoadCommodityStatus = Input_LoadCommodityStatus;
ContYardDogData.PlantLocation = Input_PlantLocation;
//Pass the inputs for new row to ContYardDog.
/*
ContYardDogAdmin ContYardDogData = new ContYardDogAdmin();
ContYardDogData.Location = NewRow_Location.ToString();
ContYardDogData.Section = NewRow_Section.ToString();
ContYardDogData.TrailerNumber = NewRow_TrailerNumber.ToString();
ContYardDogData.CarrierName = NewRow_CarrierName.ToString();
ContYardDogData.LoadCommodityStatus = NewRow_CommodityStatus.ToString();
ContYardDogData.PlantLocation = NewRow_PlantLocation.ToString();
*/
/*
string Location = ContYardDogData.Location.ToUpper();
string Section = ContYardDogData.Section.ToUpper();
string TrailerNumber = ContYardDogData.TrailerNumber.ToUpper();
string CarrierName = ContYardDogData.CarrierName.ToUpper();
string LoadCommodityStatus = ContYardDogData.LoadCommodityStatus.ToUpper();
string PlantLocation = ContYardDogData.PlantLocation;
*/
//Create Sessions to capture data.
Session["Location"] = Input_Location.ToUpper();
Session["Section"] = Input_Section.ToUpper();
Session["TrailerNumber"] = Input_TrailerNumber.ToUpper();
Session["CarrierName"] = Input_CarrierName.ToUpper();
Session["LoadCommodityStatus"] = Input_LoadCommodityStatus.ToUpper();
Session["PlantLocation"] = Input_PlantLocation;
YardDogWebGridAdmin YardDogData = new YardDogWebGridAdmin();
HttpContext.Session["LocationID"] = YardDogData.Insert(ContYardDogData);
return View(ContYardDogData);
}
//Insert a New Row.
[HttpPost]
public JsonResult InsertCustomer(LocationData customer)
{
using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
{
entities.LocationDatas.Add(customer);
entities.SaveChanges();
return Json(customer);
}
}
//Draw a Rectangle around selected Cell.
/*
private void Form1_Load(object sender, EventArgs e)
//Create a datatable for webgrid.
//https://stackoverflow.com/questions/16466487/putting-gridview-data-in-a-datatable
DataTable dt = new DataTable();
WebGridColumn webGrid = new WebGridColumn();
PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3();
LocationData locationData = new LocationData();
for (int i = 0; i < dt.Columns.Count; i++)
{
dt.Columns.Add("column" + i.ToString());
}
foreach (GridViewRow row in dt.Rows)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
dr["column" + j.ToString()] = row.Cells[j].Text;
}
dt.Rows.Add(dr);
}
//DataTable dt = new DataTable("Test Table");
dt.Columns.Add("Column 1");
dt.Columns.Add("Column 2");
dt.Columns.Add("Column 3");
dt.Columns.Add("Column 4");
dt.Columns.Add("Column 5");
dt.Rows.Add(dt.NewRow());
dt.Rows.Add(dt.NewRow());
dt.Rows.Add(dt.NewRow());
dt.Rows.Add(dt.NewRow());
dt.Rows.Add(dt.NewRow());
WebGrid DataSource = dt;
DataSource.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.MultiSelect = false;
dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.White;
dataGridView1.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.dataGridView1_CellPainting);
dataGridView1.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.dataGridView1_EditingControlShowing);
}
}
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
PW_YardDogDataEntitiesModel3 yardDog = new PW_YardDogDataEntitiesModel3();
YardDogModel model = new YardDogModel();
WebGrid webGrid = new WebGrid();
DataTable dt = new DataTable();
if (e.ColumnIndex != -1 && e.RowIndex != -1 && webGrid(e.ColumnIndex, e.RowIndex).Selected)
{
using (Brush borderBrush = new SolidBrush(Color.Red))
{
using (Pen borderPen = new Pen(borderBrush, 2))
{
Rectangle rectDimensions = e.CellBounds;
\ rectDimensions.Width -= 2;
rectDimensions.Height -= 2;
rectDimensions.X = rectDimensions.Left + 1;
rectDimensions.Y = rectDimensions.Top + 1;
e.Graphics.DrawRectangle(borderPen, rectDimensions);
e.Handled = true;
}
}
}
} */
}
//OptGroup DropDownList Box Helper. //https://dotnetgenetics.blogspot.com/2016/05/aspnet-mvc-listboxfor-with-optgroup-tag.html
public static class HtmlExtensions
{
public static IHtmlString ListBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, Dictionary<string, IEnumerable<SelectListItem>> selectList,
object htmlAttributes = null)
{
var select = new TagBuilder("select");
select.Attributes.Add("name", ExpressionHelper.GetExpressionText(expression));
if (htmlAttributes != null)
{
RouteValueDictionary routeValues = new RouteValueDictionary(htmlAttributes);
if (!routeValues.ContainsKey(("size").ToLower()))
{
select.Attributes.Add("size", selectList.Sum(x => x.Value.Count()).ToString());
}
foreach (var item in routeValues)
{
select.Attributes.Add(item.Key, item.Value.ToString());
}
}
else
select.Attributes.Add("size", selectList.Sum(x => x.Value.Count()).ToString());
var optgroups = new StringBuilder();
foreach (var kvp in selectList)
{
var optgroup = new TagBuilder("optgroup");
optgroup.Attributes.Add("label", kvp.Key);
var options = new StringBuilder();
foreach (var item in kvp.Value)
{
var option = new TagBuilder("option");
option.Attributes.Add("value", item.Value);
option.SetInnerText(item.Text);
if (item.Selected)
{
option.Attributes.Add("selected", "selected");
}
options.Append(option.ToString(TagRenderMode.Normal));
}
optgroup.InnerHtml = options.ToString();
optgroups.Append(optgroup.ToString(TagRenderMode.Normal));
}
select.InnerHtml = optgroups.ToString();
return MvcHtmlString.Create(select.ToString(TagRenderMode.Normal));
}
}
}
Model:
[/Code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ClassLibraryQualityBI.DAL;
using ClassLibraryQualityBI.Container;
using System.ComponentModel.DataAnnotations;
namespace YardDog.Model
{
public class YardDogModel
{
ContYardDogAdmin ContYardDogData = new ContYardDogAdmin();
//Two Properties for DropDownList.
public List<LocationData> LocationDatas { get; set; }
//public List<LocationData> Location { get; set; }
public List<LocationData> TrailerNumber { get; set; }
public List<SelectListItem> PlantLocation { get; set; }
public List<SelectListItem> Location { get; set; }
public List<SelectListItem> LocationList { get; set; }
public List<SelectListItem> SectionList { get; set; }
[Display(Name = "Name")]
public List<SelectListItem> Section { get; set; }
public List<SelectListItem> ListDuplicates { get; set; }
public List<SelectListItem> UserName { get; set; }
//Allow the data to be transfered (Backend into SQL Server).
[Required]
public string Input_Location { get; set; }
[Required]
public string Input_Section { get; set; }
public string Input_TrailerNumber { get; set; }
public string Input_CarrierName { get; set; }
public string Input_CommodityLoadStatus { get; set; }
[Required]
public string Input_PlantLocation { get; set; }
//YardDogModel YardDogDatas = new YardDogModel();
//string TrailerNumber = Input_TrailerNumber;
public bool SelectedMoveIsChecked { get; set; } = false;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

