How can I make a cascading dropdown list? - c#

I have Companies and Vacancies tables.
Company has n number of Vacancies. I need to make two dropdown lists.
In one it will be Company, when I select it, there will be Vacancies related to this company.
Here is model of Companies
public Company()
{
this.Clients = new HashSet<Client>();
this.Vacancies = new HashSet<Vacancy>();
}
[Key]
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string Id { get; set; }
public virtual AspNetUser AspNetUser { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Client> Clients { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Vacancy> Vacancies { get; set; }
}
Here is model for Vacancies
public partial class Vacancy
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Vacancy()
{
this.Interviews = new HashSet<Interview>();
}
[Key]
public int VacancyId { get; set; }
public string VacancyName { get; set; }
public Nullable<int> CompanyID { get; set; }
public virtual Company Company { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Interview> Interviews { get; set; }
Here is controller where I need to do this
[HttpGet]
public ActionResult WelcomeScreen()
{
// Формируем список команд для передачи в представление
SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
ViewBag.Teams = teams;
return View();
}
//Заносим инфу о вакансии в таблицу
[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
db.Interview.Add(interview);
db.SaveChanges();
//Int32 id = interview.Interview_Id;
//TempData["id"] = id;
return RedirectToAction("Index", "Questions", new { id = interview.Interview_Id });
}
How I need to make Cascade Dropdown list?
UPDATE
I try solution
Here is my controller (Questions controller)
[HttpGet]
public ActionResult WelcomeScreen()
{
// Формируем список команд для передачи в представление
//SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
//ViewBag.Teams = teams;
ViewBag.Companies = new SelectList(db.Companies, "CompanyID", "CompanyName");
return View();
}
//Заносим инфу о вакансии в таблицу
[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
db.Interview.Add(interview);
db.SaveChanges();
//Int32 id = interview.Interview_Id;
//TempData["id"] = id;
return RedirectToAction("Index", "Questions", new { id = interview.Interview_Id });
}
public ActionResult Vacancies(int companyId)
{
var items = db.Vacancy
.Where(x => x.CompanyID == companyId)
.Select(x => new SelectListItem
{
Value = x.VacancyId.ToString(),
Text = x.VacancyName
})
.ToList();
return Json(items, JsonRequestBehavior.AllowGet);
}
Here is script
<script>
$(function () {
$("#Company").change(function (e) {
var $vacancy = $("#vacancy");
var url = $vacancy.data("url") + '?companyId=' + $(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
</script>
And here is View
<div class="right-grid-in-grid">
<div style="margin-left:20px;">
#Html.DropDownList("Company", ViewBag.Companies as SelectList, new { #class = "greeting"})
#Html.ValidationMessageFor(model => model.VacancyId, "", new { #class = "text-danger" })
</div>
<div style="margin-left:20px;">
<select name="id" id="vacancy" data-url="#Url.Action("Vacancies","Questions")" class="greeting"/>
</div>
</div>
But AJAX not works.

The idea of cascading dropdown is, When you load the page, you load the dropdown content for the first SELECT element. The second SELECT element will be an empty one. When user selects an option from the first dropdown, send that to the server which returns the content needed to build the second dropdown.
So in the GET action of your page, get the data needed to render the first dropdown.
public ActionResult Welcome()
{
ViewBag.Companies = new SelectList(db.Companies, "CompanyID", "CompanyName");
return View();
}
Now in the view, you can use the DropDownList helper method to render the SELECT element with the data we set to the ViewBag.Companies. We will also add our second dropdown as well.
#Html.DropDownList("Company", ViewBag.Companies as SelectList)
<select name="id" id="vacancy" data-url="#Url.Action("Vacancies","Home")">
Now we will use some ajax code(using jQuery in this example) to get the content for the second dropdown. Register an event handler for the change event of the first dropdown, get the selected value, make an ajax call to the Vacancies action method which returns the data needed to build the second dropdown in JSON format. Use this JSON data to build the second dropdown in javascript.
$(function(){
$("#Company").change(function (e) {
var $vacancy = $("#vacancy");
var url = $vacancy.data("url")+'?companyId='+$(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
Now the last part is, implementing the Vacancies method.
public ActionResult Vacancies(int companyId)
{
var items = db.Vacancies
.Where(x=>x.CompanyID==comapnyId)
.Select(x => new SelectListItem { Value = x.VacancyId.ToString(),
Text = x.VacancyName })
.ToList();
return Json(items, JsonRequestBehavior.AllowGet);
}
Assuming db is your DbContext class object.
Ajax is not necessary for implementing cascading dropdowns. You can post the form with the selected companyId and the action method can return the same with second dropdown filled. But people usually use ajax to give a nice user experience

Related

ASP.NET MVC one of the forms dont get validation messages

My problem is this: I have created a view in which I want to be able to remove and add new identity roles. For that I created two forms that call two different actions. I have created a big model which consists of smaller models which are bound by the forms to the actions. Everything works as intended, models get bound properly, data is there and proper actions are executed as they should.
Don't get me wrong, I understand those are separate forms and I know they will never show validation messages both at the same time because only one form can be posted at a time. The problem is that when I click submit on the CreateNewRole form, the validation message is there, but when I click submit on the RemoveRoles action, I don't get any validation messages and no validation classes are applied to the html elements, there is the usual "field-validation-valid" and no "field-validation-error" class in it while its perfectly present in CreateNewRole.
Why does validation work on the first form but not on the second form? I cant find any difference in how i made those two forms, am i not noticing something?
When I debug modelstate of the RemoveRoles action, the error is there, but somehow the view isn't getting informed of it.
View
#model Models.ViewModels.RolePanelViewModel
#using Extensions
<h2>Role Panel</h2>
<article>
<div class="admin-panel-flex-container">
<div class="form-container">
#using (Html.BeginForm("CreateNewRole", "Administrator"))
{
<div class="form-group">
#Html.LabelFor(l => l.NewRoleRolePanelViewModel.NewIdentityRole.Name)
#Html.TextBoxFor(t => t.NewRoleRolePanelViewModel.NewIdentityRole.Name)
#Html.ValidationMessageFor(t => t.NewRoleRolePanelViewModel.NewIdentityRole.Name)
<button type="submit">Dodaj role</button>
</div>
}
</div>
<div class="form-container">
#using (Html.BeginForm("RemoveRoles", "Administrator"))
{
<div class="form-group">
#Html.LabelFor(l => l.ListRolePanelViewModel.SelectedIdentityRoles)
#Html.ListBoxFor(l => l.ListRolePanelViewModel.SelectedIdentityRoles, #Model.ListRolePanelViewModel.IdentityRolesSelectListItems)
#Html.ValidationMessageFor(t => t.ListRolePanelViewModel.SelectedIdentityRoles)
<button type="submit">Skasuj wybrane</button>
</div>
}
</div>
</div>
</article>
Models
public class RolePanelViewModel
{
public ListRolePanelViewModel ListRolePanelViewModel { get; set; }
public NewRoleRolePanelViewModel NewRoleRolePanelViewModel { get; set; }
}
public class ListRolePanelViewModel
{
public List<IdentityRoleDTO> IdentityRoles { get; set; }
public List<SelectListItem> IdentityRolesSelectListItems { get; set; }
[Required(ErrorMessage = "Należy wybrać przynajmniej jedną pozycję z listy")]
public List<string> SelectedIdentityRoles { get; set; }
}
public class NewRoleRolePanelViewModel
{
public IdentityRoleDTO NewIdentityRole { get; set; }
}
public class IdentityRoleDTO
{
public string Id { get; set; }
[Required(ErrorMessage = "Nowa rola musi mieć nazwę")]
[MinLength(5)]
public string Name { get; set; }
public List<IdentityUserRole> Users { get; set; }
}
Actions
public ActionResult OpenRolePanel()
{
var roles = _context.Roles.ToList();
var viewModel = new RolePanelViewModel
{
ListRolePanelViewModel = new ListRolePanelViewModel
{
IdentityRolesSelectListItems = GetSelectListItems(roles,
(a) => new SelectListItem {Value = a.Id.ToString(), Selected = false, Text = a.Name})
},
NewRoleRolePanelViewModel = new NewRoleRolePanelViewModel()
};
return View("RolePanel", viewModel);
}
[HttpPost]
public async Task<ActionResult> CreateNewRole(NewRoleRolePanelViewModel newRoleRolePanelViewModel)
{
if(!ModelState.IsValid)
{
var roles = _context.Roles.ToList();
var viewModel = new RolePanelViewModel
{
ListRolePanelViewModel = new ListRolePanelViewModel
{
IdentityRolesSelectListItems = GetSelectListItems(roles,
(a) => new SelectListItem { Value = a.Id.ToString(), Selected = false, Text = a.Name })
},
NewRoleRolePanelViewModel = newRoleRolePanelViewModel
};
return View("RolePanel", viewModel);
}
var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
var roleManager = new RoleManager<IdentityRole>(roleStore);
await roleManager.CreateAsync(new IdentityRole(newRoleRolePanelViewModel.NewIdentityRole.Name));
return View("RolePanel");
}
[HttpPost]
public ActionResult RemoveRoles(ListRolePanelViewModel listRolePanelViewModel)
{
if (!ModelState.IsValid)
{
var roles = _context.Roles.ToList();
var viewModel = new RolePanelViewModel
{
ListRolePanelViewModel = listRolePanelViewModel,
NewRoleRolePanelViewModel = new NewRoleRolePanelViewModel()
};
viewModel.ListRolePanelViewModel.IdentityRolesSelectListItems = GetSelectListItems(roles,
(a) => new SelectListItem {Value = a.Id.ToString(), Selected = false, Text = a.Name});
return View("RolePanel", viewModel);
}
return View("RolePanel");
}
Custom method that may be needed if you want to run the code
private List<SelectListItem> GetSelectListItems<T>(List<T> dbSetResult, Func<T,SelectListItem> Func)
{
var result = new List<SelectListItem>();
foreach (var item in dbSetResult)
{
result.Add(Func(item));
}
return result;
}

Related DropDownList's with Ajax

I'm trying to do this:
choose an item in the first ddl, and then appears a list of related items in the second ddl. I'm using this method: How to keep cascade dropdownlist selected items after form submit?
But I can't handle it and something is wrong(with Ajax I guess) and I have only a list of cities for the first ddl, the second ddl is empty. Please, help.
My view:
#model Bike_Store.Models.OrderVM
#{
ViewBag.Title = "Checkout";
}
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var url = '#Url.Action("FetchAddresses")';
var adresses = $('#Delivery_id');
$('#Cities_id').change(function () {
if (!$(this).val()) {
return;
}
$.getJSON(url, { id: $(this).val() }, function (data) {
adresses.empty().append($('<option></option>').val('').text('-Please select-'));
$.each(data, function (index, bs_delivery_type) {
subLocalities.append($('<option></option>').val(item.Value).text(item.Text));
});
});
});
</script>
#using (#Html.BeginForm())
{
#Html.LabelFor(m=>m.Cities_id)
#Html.DropDownListFor(m=>m.Cities_id, Model.CitiesList, "-Please select-")
#Html.ValidationMessageFor(m=>m.Cities_id)
#Html.LabelFor(m=>m.Delivery_id)
#Html.DropDownListFor(m=>m.Delivery_id, Model.DeliveriesList, "-Please Select-")
#Html.ValidationMessageFor(m=>m.Delivery_id)
}
Model:
public class OrderVM
{
[Required(ErrorMessage = "Address")]
public decimal? Cities_id { get; set; }
[Required(ErrorMessage = "City")]
public decimal? Delivery_id { get; set; }
public SelectList CitiesList { get; set; }
public SelectList DeliveriesList { get; set; }
}
Controller:
private void ConfigureViewModel(OrderVM model)
{
IEnumerable<bs_cities> cities = _db.bs_cities;
model.CitiesList = new SelectList(cities, "cities_id", "cities_name");
if (model.Cities_id.HasValue)
{
IEnumerable<bs_delivery_type> addresses = _db.bs_delivery_type.Where(x => x.delivery_city_id == model.Cities_id.Value);
model.DeliveriesList = new SelectList(addresses, "delivery_id", "delivery_address");
}
else
{
model.DeliveriesList = new SelectList(Enumerable.Empty<SelectListItem>());
}
}
public ViewResult Checkout()
{
OrderVM model = new OrderVM();
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ViewResult Checkout(OrderVM model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
else
{
return View("123");
}
}
public JsonResult FetchSubLocalities(int ID)
{
var bs_delivery_type = _db.bs_cities.Where(x => x.cities_id == ID).Select(c => new
{
Value = c.cities_id,
Name = c.cities_name
});
return Json(bs_delivery_type, JsonRequestBehavior.AllowGet);
}

asp.net mvc Html.DropDownListFor: how to handle selected id

I have a problem with using #Html.DropDownListFor element.
What i have:
Model 'DatabaseModel':
public class DirectionEntity
{
public string Id { get; set; }
public string DirectionName { get; set; }
}
public class ViewModel
{
public int SelectedDirectionID { get; set; }
public List<DirectionEntity> DirectionList { get; set; }
}
Model 'DataFactory':
public class DataFactory
{
public static ViewModel Refresh()
{
using (var db = new MyDatabase())
{
return new ViewModel()
{
DirectionList = db.Directions.Select(_ => new { _.Id, _.DirectionName })
.ToList()
.Select(_ => new DirectionEntity() { Id = _.Id.ToString(), DirectionName = _.DirectionName })
.ToList(),
};
}
}
}
Controller:
public System.Web.Mvc.ActionResult AddNewDocument()
{
var db = DataFactory.Refresh();
return View(db);
}
[HttpPost]
public System.Web.Mvc.ActionResult AddNewEntry(ViewModel m)
{
m = DataFactory.Save(m);
ModelState.Clear();
return View(<some view>);
}
View:
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.SelectedDirectionID, new SelectList(Model.DirectionList.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.DirectionName }), "Value", "Text"), new { #class = "Duration", required = "required" })
<button type="submit" class="btn btn-default SaveAll">Save</button>
}
The question:
How to handle 'SelectedDirectionID' value, after user selected some position on dropdownlist, but not yet sent the request to the server using a POST-method.
See what the id of your dropdown is and then you can subscribe to the change event on the client side. You can do this using jQuery.
$("#idOfYourDropDown").change(function () {
// Do whatever you need to do here
// Here are some ways you can get certain things
var end = this.value;
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
});
Also you should see my answer here on why you should not return a view from a POST action the way you are.
In this case you have to use Jquery. As per your view id for your drop down is 'SelectedDirectionID';
Your Js:
$(document).ready(function () {
var selectedValue = $('#SelectedDirectionID').val();
var selectedText = $("#SelectedDirectionID option:selected").text();
});
Or Inside drop down change event.
$('#SelectedDirectionID').change(function () {
var selectedValue = $(this).val();
var selectedText = $(this).find("option:selected").text();
});

ASP.NET MVC Edit CheckBoxList values in Database

I'm having trouble understanding how to retrieve and edit the DevId values from my CustomerDevice table in my database to the CheckBoxList based on the CustId value.
My Index Action Method for the CustomerDeviceController displays a list of Customers from my Customers table. I have an ActionLink labeled "Edit" that passes the CustId value to the CustomerDeviceController [HttpGet] Edit(int? id) Action Method which currently displays all CheckBoxListItem values from the Devices table. However, the CheckBoxList does not display the checked DevId values from the CustomerDevice table in the database to the CheckBoxList that pertain to the CustId, instead it displays a check for each of the CheckBoxList values.
The part that I'm having trouble understanding and figuring out, is how can I display the selected DevId values from the CustomerDevice table in my database to the CheckBoxList based on the CustId and then Edit/Update the modified CheckBoxListItems on the [HttpPost] Edit Action Method back to my CustomerDevice table in my database if need be.
Please see the following code below that I have so far.
Models
public class CheckBoxListItem
{
public int ID { get; set; }
public string Display { get; set; }
public bool IsChecked { get; set; }
}
public class Customer
{
public int CustId { get; set; }
public string CustDisplayName { get; set; }
public string CustFirstName { get; set; }
....
}
public class Device
{
public int DevId { get; set; }
public string DevType { get; set; }
}
public class CustomerDevice
{
public int CustId { get; set; }
public int DevId { get; set; }
public Customer Customer { get; set; }
public Device Device { get; set; }
}
ViewModels
public class CustomerDeviceFormViewModel
{
public int CustId { get; set; }
public string CustDisplayName { get; set; }
public List<CheckBoxListItem> Devices { get; set; }
}
CustomerDeviceController
public ActionResult Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var customervm = new CustomerDeviceFormViewModel();
Customer customer = db.Customers.SingleOrDefault(c => c.CustId == id);
if (customer == null)
{
return NotFound();
}
customervm.CustId = customer.CustId;
customervm.CustDisplayName = customer.CustDisplayName;
// Retrieves list of Devices for CheckBoxList
var deviceList = db.Devices.ToList();
var checkBoxListItems = new List<CheckBoxListItem>();
foreach (var device in deviceList)
{
checkBoxListItems.Add(new CheckBoxListItem()
{
ID = device.DevId,
Display = device.DevType,
IsChecked = deviceList.Where(x => x.DevId == device.DevId).Any()
});
}
customervm.Devices = checkBoxListItems;
return View(customervm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CustomerDeviceFormViewModel vmEdit)
{
if (ModelState.IsValid)
{
Customer customer = db.Customers.SingleOrDefault(c => c.CustId == vmEdit.CustId);
if (customer == null)
{
return NotFound();
}
foreach (var deviceId in vmEdit.Devices.Where(x => x.IsChecked).Select(x => x.ID))
{
var customerDevices = new CustomerDevice
{
CustId = vmEdit.CustId,
DevId = deviceId
};
db.Entry(customerDevices).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(vmEdit);
}
Edit.chtml
<div class="form-group">
Please select the Devices to assign to <b>#Html.DisplayFor(c => c.CustDisplayName)</b>
</div>
<div class="form-group">
#Html.EditorFor(x => x.Devices)
</div>
#Html.HiddenFor(c => c.CustId)
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
Shared/EditorTemplate/CheckBoxListItem.chtml
<div class="checkbox">
<label>
#Html.HiddenFor(x => x.ID)
#Html.CheckBoxFor(x => x.IsChecked)
#Html.LabelFor(x => x.IsChecked, Model.Display)
</label>
<br />
Your code for setting the IsChecked value will always return true (your loop is basically say if the collection contains me (which of course it does) then set it to true).
You need to get the selected values for each Customer by reading the values from your CustomerDevice table
Customer customer = db.Customers.SingleOrDefault(c => c.CustId == id);
if (customer == null)
{
return NotFound();
}
// Get all devices
var deviceList = db.Devices.ToList();
// Get the selected device ID's for the customer
IEnumerable<int> selectedDevices = db.CustomerDevices
.Where(x => x.CustId == id).Select(x => x.DevId);
// Build view model
var model = new CustomerDeviceFormViewModel()
{
CustId = customer.CustId,
CustDisplayName = customer.CustDisplayName,
Devices = deviceList.Select(x => new CheckBoxListItem()
{
ID = x.DevId,
Display = x.DevType,
IsChecked = selectedDevices.Contains(x.DevId)
}).ToList()
};
return View(model);
Here's a snippet of Razor code that I've used:
foreach (SelectListItem p in Model.PositionList)
{
#Html.Raw(p.Text + "<input type=checkbox name=\"PositionIDs\" id=\"PositionIDs\" value=" + #p.Value + (Model.Positions != null && Model.Positions.Any(pos => pos.ScoreCardId == Convert.ToInt32(p.Value)) ? " checked />" : " />"));
}
You might want to have a look at the MvcCheckBoxList NuGet package:
https://www.nuget.org/packages/MvcCheckBoxList/
This makes doing some powerful stuff with a CheckBoxList much easier in MVC - and may be a better approach to fixing your CheckBox issues.

three level cascading drop down list

I am a beginner in programming being stuck the last 2 days on that and i am hopping on your help :)
I am building an mvc 4 app and I have a partial view with a list of departments and when you choose the department you can see the item types for this specific department in a drop down list in Browse view.
What I am trying to make is one more dropdown list in Browse view that will show the items according to the selected department and item types.
So this is my code :
View :
#using (Html.BeginForm("Browse", "Bookings", FormMethod.Post, new { id = "TypeItemFormID", data_itemsListAction = #Url.Action("ItemsList") }))
{
<fieldset>
<legend> Type/Item</legend>
#Html.DropDownList("department", ViewBag.ItemTypesList as SelectList, "Select a Type", new {id="ItemTypeID"})
<div id="ItemsDivId">
<label for="Items">Items </label>
<select id="ItemsID" name="Items"></select>
</div>
<p>
<input type ="submit" value="Submit" id="SubmitID" />
</p>
</fieldset>
}
<script src ="#Url.Content("~/Scripts/typeItems.js")"></script>
The controller :
public class BookingsController : Controller
{
private BookingSystemEntities db = new BookingSystemEntities();
//
// GET: /Bookings/
public ActionResult Index()
{
ViewBag.Message = "Select your Department";
var departments = db.Departments.ToList();
return View(departments);
}
public ActionResult Browse(string department, string ID)
{
ViewBag.Message = "Browse for Equipment";
var departments = db.Departments.Include("Items").Single(i => i.DepartmentName == department);
ViewBag.ItemTypesList = GetItemTypeSelectList(department);
return View();
}
public ActionResult Details(int id)
{
var item = db.Items.Find(id);
return View(item);
}
//
// GET: /Home/DepartmentMenu
[ChildActionOnly]
public ActionResult DepartmentMenu()
{
var departments = db.Departments.ToList();
return PartialView(departments);
}
public SelectList GetItemTypeSelectList(string department)
{
var departments = db.Departments.Include("Items").Single(i => i.DepartmentName == department);
List<SelectListItem> listItemTypes = new List<SelectListItem>();
foreach (var item in departments.Items.Select(s => s.ItemType.ItemTypeName).Distinct())
{
listItemTypes.Add(new SelectListItem
{
Text = item,
Value = item,
}
);
}
return new SelectList(listItemTypes.ToArray(),
"Text",
"Value");
}
public ActionResult ItemsList(string ID)
{
string Text = ID;
var items = from s in db.Items
where s.ItemType.ItemTypeName == Text
select s;
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
items.ToArray(),
"ItemId",
"ItemName")
, JsonRequestBehavior.AllowGet);
return RedirectToAction("Browse");
}
}
The Javascript :
$(function () {
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').change(function () {
var URL = $('#TypeItemFormID').data('itemsListAction');
$.getJSON(URL + '/' + $('#ItemTypeID').val(), function (data) {
var items = '<option>Select a Item</option>';
$.each(data, function (i, item) {
items += "<option value='" + item.Value + "'>" + item.Text + "</option>";
// state.Value cannot contain ' character. We are OK because state.Value = cnt++;
});
$('#ItemsID').html(items);
$('#ItemsDivId').show();
});
});
$('#ItemsID').change(function () {
$('#SubmitID').show();
});
});
And at last my Model :
public class Department
{
public int DepartmentId { get; set; }
[DisplayName("Department")]
public string DepartmentName { get; set; }
public List<Item> Items { get; set; }
}
public class ItemType
{
public int ItemTypeId { get; set; }
[DisplayName("Type")]
public string ItemTypeName { get; set; }
[DisplayName("Image")]
public string ItemTypeImage { get; set; }
public List<Item> Items { get; set; }
}
public class Item
{
public int ItemId { get; set; }
[DisplayName("Name")]
public string ItemName { get; set; }
[DisplayName("Description")]
public string ItemDescription { get; set; }
[DisplayName("Ref Code")]
public string ItemReferenceCode { get; set; }
[ForeignKey("ItemType")]
public int ItemTypeId { get; set; }
public virtual ItemType ItemType { get; set; }
[ForeignKey("Department")]
public int DepartmentId { get; set; }
public Department Department { get; set; }
[DisplayName("Computer Location")]
public string ComputerLocation { get; set; }
[DisplayName("Author Name")]
public string AuthorName { get; set; }
[DisplayName("Published Year")]
public string PublishedYear { get; set; }
}
Here's how I would accomplish something like this. It isn't the only way to do it.
$('#ItemTypeID').on('change', function() {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function(results) {
var options = $('#ItemTypeFormId');
options.empty();
options.append($('<option />').val(null).text("- Select an Item Type -"));
$.each(results, function() {
options.append($('<option />').val(this.ItemTypeFormId).text(this.Value));
});
}
});
});
Then you'd have a controller that looks something like this.
[HttpPost]
public JsonResult GetItemTypeForm(string itemTypeId)
{
//pseudo code
var data = Repostitory.GetData(itemTypeId)
return Json(data);
}

Categories

Resources