Dependent dropdownlist in ASP.NET MVC - c#

At present I have two tables (Teams and Employees)
I am populating the dropdownList for Teams perfectly, next I am trying to populate the second dropdownlist depending on the selectedId of Teams for Employees.
Controller:
// GET: CalView
public ActionResult Index(string ses, string DH)
{ //Team Lead Members
var eID = Convert.ToInt32(Session["currentEmployeeID"]);
var EmpID = Session["currentEmpID"];
Employee obj = (from o in db.Employees
where o.EnrollNumber == EmpID
select o).FirstOrDefault();
Department dept = (from dep in db.Departments
where dep.LeadBy == obj.EmployeeId
select dep).FirstOrDefault();
//this works fine
ViewBag.showTeams = new SelectList(db.Teams.Where(tm => (tm.DeptID == dept.DepartmentId) && (dept.LeadBy == eID)), "TeamID","Name");
//this obviously does not
ViewBag.showMembers = new SelectList(db.Employees.Where(empt => (empT.TeamID == selectedIdFromPreviousDropDownList), "EmployeeID", "Employee"));
return View();
}
View:
if ((Session["UT"] == "DD") && (#ViewBag.DeptLead != null))
{
//this works
#Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { #class = "form-control" })
//this does not work
#Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new { #class = "form-control" })
}
Do I need some AJAX call? or perhaps a POST method? Totally new to MVC.

Do I need some AJAX call? or perhaps a POST method? Okay then, lets do it this way:
Give your DropdownLists some id's probably:
#Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { id = "ddshowTeams", #class = "form-control" })
#Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new {id = "ddshowMembers", #class = "form-control" })
Create a jsonResult function, GetMembers and some Magic right there:
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#ddshowTeams").change(function () {
console.log("pehla andar");
$("#ddshowMembers").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetMembers")',
dataType: 'json',
data: { id: $("#ddshowTeams").val() },
success: function (mems) {
console.log("wich ayaeee");
// states contains the JSON formatted list
// of states passed from the controller
$.each(mems, function (i, member) {
$("#ddshowMembers").append('<option value="'
+ member.Value + '">'
+ member.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
and in your controller:
public JsonResult GetMembers(int id)
{
return Json(new SelectList(db.Employees.Where(empt => (empt.TeamId == id)), "EmployeeID", "FirstName"));
}

Related

Auto populate Textbox based on Dropdown selection

I want to auto-populate a textbox based on dropdown selection in MVC, using jquery, razor view and controller, from a model called Supplier, that has SupplierID, and Company_Registration_Number as variables. I have managed to do it as cascade dropdown, but i'm failingto populate #Html.EditorFor.
My controller :
public JsonResult GetCompanyRegistrationNumberId(int id)
{
var suppliers = db.Suppliers.Where(p => p.SupplierID == id).ToList();
var result = (from r in suppliers
select new
{
id = r.SupplierID,
name = r.Company_Registration_Number
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
My JQuery:
$(function () {
if ($("#SupplierID").val() == '0') {
var productDefaultValue = "<option value='0'>--Select a category first--</option>";
$("#Company_Registration_Number").html(productDefaultValue).show();
}
$("#SupplierID").change(function () {
var selectedItemValue = $(this).val();
alert("cert");
var ddlProducts = $("#Company_Registration_Number");
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("GetCompanyRegistrationNumberId", "Order")',
data: { "id": selectedItemValue },
success: function (data) {
ddlProducts.html('');
$.each(data, function (id, option) {
ddlProducts.append($('<option></option>').val(option.id).html(option.name));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Found error to load product!!.');
}
});
});
});
My Razor view:
<div class="form-group">
#Html.LabelFor(model => model.Company_Registration_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Company_Registration_Number, new { #id = "Company_Registration_Number" })
#Html.ValidationMessageFor(model => model.Company_Registration_Number, "", new { #class = "text-danger" })
</div>
</div>
Thanks in advance.

Cascading Drop Down List - ASP.NET MVC

I work with ASP.NET MVC and I have an ODBC connection for database and have retrieved two drop down list from controller to view using queries.
Those two drop down lists are:
#Html.DropDownListFor(model => model.storageLocation, new SelectList(Model.locationGroupDD, "storageLocation", "storageLocation"), "Choose Location Group", new { #id = "storageLocation", #class = "dropdown1" })
#Html.DropDownListFor(model => model.storageLocationList, new SelectList(Model.locationDD,"storageLocationList","storageLocationList"), "Choose Location", new { #id = "storageLocationListDropDown", #class = "dropdown1" })
I'm new to JQuery and not sure how to script this. However, I found this script online and tried using the following to make necessary changes but I literally don't know how to modify/proceed. Any help is appreciated! Thank you.
Following are the queries I used to retrieve the data from database:
For drop downlist 1: select abc from xyz;
For drop downlist 2: select pqr from lmn where abc = "some value";
I want to pass the selected value from drop down list 1 to controller to execute query for second drop down list.
Please follow the following steps to make Cascading DropdownList in ASP.NET MVC:
1. In your Controller:
public class YourControlleNameController : Controller
{
public ActionResult Create()
{
var LocationGroupDDList = _dbContext.LocationGroupDD.Select(lgdd =>
new { lgdd.LocationGroupDDId, lgdd.LocationGroupDDName }).ToList();
ViewBag.LocationGroupDDSelectList = new SelectList(LocationGroupDDList, "LocationGroupDDId", "LocationGroupDDName");
ViewBag.LocationDDListSelectList = new SelectList(new List<LocationDD>(), "LocationDDId", "LocationDDName");
return View();
}
[HttpPost]
public ActionResult Create(YourModel model, string LocationGroupDDId)
{
if (ModelState.IsValid)
{
// Do necessary staff here
}
var LocationGroupDDList = _dbContext.LocationGroupDD.Select(lgdd =>
new { lgdd.LocationGroupDDId, lgdd.LocationGroupDDName }).ToList();
ViewBag.LocationGroupDDSelectList = new SelectList(LocationGroupDDList, "LocationGroupDDId", "LocationGroupDDName",LocationGroupDDId);
var LocationDDList = _dbContext.LocationDD.Where(ldd => ldd.LocationGroupDDId == LocationGroupDDId).Select(ldd => new {ldd.LocationDDId, ldd.LocationDDName}).ToList();
ViewBag.LocationDDListSelectList = new SelectList(LocationDDList, "LocationDDId", "LocationDDName",model.LocationDDId);
return View();
}
public JsonResult GetLocationDDByLocationGroupDD(string LocationGroupDDId)
{
var LocationDDList = _dbContext.LocationDD.Where(ldd => ldd.LocationGroupDDId == LocationGroupDDId)
.Select(ldd => new {ldd.LocationDDId, ldd.LocationDDName}).ToList();
return Json(LocationDDList, JsonRequestBehavior.AllowGet);
}
}
2. In the View:
<div class="form-group">
#Html.Label("LocationGroupDD", "Location GroupDD Name", htmlAttributes: new { #class = "control-label" })
#Html.DropDownList("LocationGroupDDId", ViewBag.LocationGroupDDSelectList as SelectList, "Select Location GroupDD", htmlAttributes: new { #class = "form-control", #id = "LocationGroupDD" })
</div>
<div class="form-group">
#Html.Label("LocationDD", "LocationDD Name", htmlAttributes: new { #class = "control-label" })
#Html.DropDownList("LocationDDId", ViewBag.LocationDDListSelectList as SelectList, "Select LocationDD", htmlAttributes: new { #class = "form-control", #disabled = "disabled", #id = "LocationDD" })
</div>
3. jQuery in the view:
#section Scripts {
<script type="text/javascript">
$(document).on('change','#LocationGroupDD', function(){
var LocationGroupDDId = $(this).val();
$('#LocationDD').empty();
if (LocationGroupDDId) {
$.ajax({
type: "GET",
url: '#Url.Action("GetLocationDDByLocationGroupDD", "YourControlleName")',
data: { LocationGroupDDId: LocationGroupDDId},
success: function(data) {
if (data.length > 0) {
$('#LocationDD').prop("disabled", false);
$('#LocationDD').append($("<option>").val("").text("Select LocationDD"));
$(data).each(function(index, item) {
$('#LocationDD').append($("<option>").val(item.LocationDDId).text(item.LocationDDName));
});
} else {
$('#LocationDD').append($("<option>").val("").text("LocationDD List Is Empty"));
}
}
});
} else {
$('#LocationDD').prop("disabled", true);
$('#LocationDD').append($("<option>").val("").text("Select Location GroupDD First"));
}
});
</script>
}
Hope this will solve your problem!

Validate Required on Non Model MVC Dropdownlist

I have a Dropdownlist from a Viewbag and I need to validate it like "Required"
My Controller
public ActionResult EsperaPorHora()
{
var cliente = new UsuarioData().Id_LicenciadoPorId(User.Identity.GetUserId());
var Cli = !string.IsNullOrEmpty(cliente.ToString()) ? Convert.ToInt32(cliente) : 0;
var cliData = new LicenciadoData();
var agora = DateTime.Now;
ViewBag.Data1 = agora.ToShortDateString();
ViewBag.Data2 = agora.ToShortDateString();
if (Cli != 0)
{
ViewBag.IdCliente = new SelectList(cliData.ListaClienteId(Cli), "Id", "Fantasia");
}
else
{
ViewBag.IdCliente = new SelectList(cliData.ListarClientes(), "Id", "Fantasia");
}
return View();
}
[HttpGet]
public JsonResult EsperaHora(string data1, string data2, int? cliente)
{
var voiceData = new KiperVoiceData(cliente);
var media = voiceData.GetEsperaData(data1, data2);
var atend = voiceData.GetEsperaHora(data1, data2);
var result = new { atend, media };
return Json(result, JsonRequestBehavior.AllowGet);
}
I tried:
#Html.DropDownList("IdCliente", null, "SELECIONE A EMPRESA", htmlAttributes: new { #class = "form-control combo2", #required = "required" })
#Html.DropDownList("IdCliente", null, "SELECIONE A EMPRESA", htmlAttributes: new { #class = "form-control combo2", #required = true })
#Html.DropDownList("IdCliente", null, "SELECIONE A EMPRESA", htmlAttributes: new { #class = "form-control combo2", required = true })
But no one worked to me, if I click button without select it run to an exception. What im doing wrong?
Send the required as a class like this:
Update
Use an overload with optionlabel. I am passing "choose" here, but you can pass whatever you need. Also put a validation summary to inform the user it is a required field.
#Html.ValidationSummary()
#Html.DropDownList("name", new List<SelectListItem> { new SelectListItem { Text = "1", Value = "2" } }, "choose", htmlAttributes: new { #class = "form-control combo2 required", #data_val = "true", #data_val_required = "choose is a required field" })
Solve the situation on html and razor is important, primarily to improve my knowledge. As I told above, I could find a solution using Js and a component named Sweet Alert as follow:
var data1 = $('#data1').val();
var data2 = $('#data2').val();
var cliente = $('#IdCliente option:selected').val();
if (cliente != "") {
$.ajax({
url: '',
dataType: "json",
type: "GET",
data: { 'data1': data1, 'data2': data2, 'cliente': cliente },
success: function (data) {
}
},
error: function (xhr) {
alert('error');
}
});
}
else {
swal({ type: "warning", title: "Alerta", text: "Selecione uma empresa por favor!", timer: 5000, showConfirmButton: true });
}
This is the result:

How to return Multiple Parameters using json in mvc4?

Hi I have four fields in my view CustomerName, ContactPerson, Email, MobileNo
CustomerName , ContactPerson are Cascading Dropdown and Email and MobileNo are textboxes.
If I select the CustomerName related ContactPerson will load automatically load in ContactPerson dropdown.
If i select the Contactperson the ContactPerson related Email and PhoneNo will load automatically in Email and PhoneNo textbox. I did this all task completely and all are working fine. Now what i need is i wish to reduce the code .
My Controller Code
public JsonResult GetCustomers()
{
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetContactPersobByCustomerId(string customerId)
{
Guid Id = Guid.Parse(customerId);
var customercontacts = (from a in db.CustomerContacts where a.CustomerID == Id select a);
return Json(customercontacts, JsonRequestBehavior.AllowGet);
}
public JsonResult GetEmailByContactPersonID(Guid CustomerContactId)
{
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
var contact1 = (from p in db.Contacts where p.ContactID == ContactID select p).FirstOrDefault().Email1;
if (contact1 == null)
{
var contact2 = (from a in db.Contacts where a.ContactID == ContactID select a).FirstOrDefault().Email2;
contact1 = contact2;
}
return Json(contact1, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPhoneNoByContactPersonID(Guid CustomerContactId)
{
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
var mobile1 = (from pn in db.Contacts where pn.ContactID == ContactID select pn).FirstOrDefault().Mobile1;
if (mobile1 == null)
{
var mobile2 = (from a in db.Contacts where a.ContactID == ContactID select a).FirstOrDefault().Mobile2;
mobile1 = mobile2;
}
return Json( mobile1, JsonRequestBehavior.AllowGet);
}
My View Code
#Html.Label("Customer Name", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerID, new SelectList(string.Empty, "Value", "Text"), "Please select a Customer", new { #class = "form-control required", type = "text" })
#Html.Label("Contact Person", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerContactID, new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { #class = "form-control", type = "text", id = "CustomerContactID" })
#Html.LabelFor(model => model.MobileNo, new { #class = "control-label" })
#Html.TextBoxFor(model => model.MobileNo, new { #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.MobileNo)
#Html.LabelFor(model => model.Email, new { #class = "control-label" })
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Email)
My Json Code
<script src="~/Scripts/jquery-ui-1.11.0.js"></script>
<script>
$(function () {
$.ajax(
'#Url.Action("GetCustomers", "VisitorsForm")',{
type: "GET",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
$('#CustomerID').change(function () {
$('#CustomerContactID').empty();
$.ajax(
'#Url.Action("GetContactPersobByCustomerId", "VisitorsForm")',{
type: "POST",
datatype: "Json",
data: { CustomerID: $('#CustomerID').val() },
success: function (data) {
$('#CustomerContactID').append($('<option></option>').val('').text('Please select'));
$.each(data, function (index, value) {
$('#CustomerContactID').append('<option value="' + value.CustomerContactID + '">' + value.ContactReference + '</option>');
});
}
});
});
});
$("#CustomerContactID").change(function () {
alert("hhh");
$.ajax(
'#Url.Action("GetEmailByContactPersonID", "VisitorsForm")',{
type: "GET",
dataType: "json",
async: false,
data: { CustomerContactID: $("#CustomerContactID").val()
},
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#Email").val(data);
}
});
});
$("#CustomerContactID").change(function () {
alert("hhh");
$.ajax(
'#Url.Action("GetPhoneNoByContactPersonID", "VisitorsForm")',{
type: "GET",
dataType: "json",
async: false,
data: { CustomerContactID: $("#CustomerContactID").val()
},
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#MobileNo").val(data);
}
});
});
See my coding i wrote separate json and jquery , ajax code for Email and PhoneNo. I feel it is not good . I wish to short my code. I want to pass multiple parameter using json. I want to pass the Email and phone while selecting the ContatcPerson in ContactPerson dropdown. it also effect performance of my application. please any one give solution and suggestion for my problem.
Advance Thanks..
Why don't you return an object from your controller that contains all the information that you need?
Any object serialized to Json can be returned as a JsonResult.
You could even do anonymous types like:
var details = new { email = "test#test.com", phone = "1234567"};
return Json(details);

Selected values in cascading dropdownlists reset on post

I have MVC4 web-application with 2 cascading dropdownlists (parent and child) and button with post action for filtering data dislpayed in grid depending on selected values in dropdownlists. Cascading dropdownlists I realized with Microsoft AJAX (Ajax.BeginForm helper), almost as described here: http://weblogs.asp.net/raduenuca/archive/2011/03/20/asp-net-mvc-cascading-dropdown-lists-tutorial-part-3-cascading-using-microsoft-ajax-ajax-beginform-helper.aspx. BTW, dropdownlists are located in partial view.
The problem is that when I click button, postback is performed and selected values in cascading dropdownlists are reset to original values, i.e. "Please, select value".
Does anybody know how to solve this problem?
Thanks in advance for all who give an answers!
Here is my code with partial view with cascading dropdownlists:
<script type="text/javascript">
$(function () {
$('#Sections').change(function () {
var sectionId = $("#Sections :selected").val();
if (sectionId != "") {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetDocumentTypesList", "DocumentTypes")',
data: { "id": sectionId },
dataType: "json",
success: function (data) {
var items = "";
$.each(data, function (i, documentType) {
items += "<option value='" + documentType.Value + "'>" + documentType.Text + "</option>";
});
$('#Types').html(items);
},
error: function (result) {
alert('Service call failed: ' + result.status + ' Type :' + result.statusText);
}
});
}
else {
var items = '<option value="">Select</option>';
$('#Types').html(items);
}
});
});
#Html.DropDownList("Sections", new SelectList(ViewBag.Sections, "Id", "Name"), "Please select parent type", new { id = "Sections" })
#Html.DropDownList("Types", new SelectList(ViewBag.Types, "Id", "Name"), "Please select child type", new { id = "Types" })
And here is controller code for partial view:
public class DocumentTypesController : Controller
{
static List<DocumentType> documentTypes = DocumentsDAL.GetDocumentTypes(true, true, false);
// GET: /DocumentTypes/
public ActionResult Index()
{
var root = documentTypes.Where(d => d.ParentId == null).ToList();
ViewBag.Sections = root;
ViewBag.Types = new List<DocumentType> { new DocumentType { Id = -1, Name = "Select" } };
return PartialView("~/Views/Shared/_DocumentTypes.cshtml", root);
}
// Get values for parent dropdownlist.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetDocumentTypesList(string id)
{
var items = GetDocumentTypes(Convert.ToInt32(id)).Select(a => new SelectListItem
{
Text = a.Name,
Value = a.Id.ToString(CultureInfo.InvariantCulture)
});
return Json(items, JsonRequestBehavior.AllowGet);
}
// Get values for child dropdownlist.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetDocumentTypeData(string sectionId, string typeId)
{
var documentTypeData = GetDocumentTypes(Convert.ToInt32(sectionId))
.First(d => d.Id == Convert.ToInt32(typeId));
return Json(documentTypeData, JsonRequestBehavior.AllowGet);
}
private static IEnumerable<DocumentType> GetDocumentTypes(int id)
{
return documentTypes.First(d => d.Id == id).DocumentTypes;
}
}
And this is a base view where it's used partial one:
#using (Ajax.BeginForm("Index", null, new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "documentsGrid"
}, new { #class = "form-inline" }))
{
<div>
#{ Html.RenderAction("Index", "DocumentTypes", new { area = "" }); }
</div>
<p class="form-inline">
#Html.LabelForModel(#Resources.LabelPeriodFrom)
#Html.Raw(" ")
#Html.TextBox("periodFrom", "", new { #class = "input-small" })
#Html.Raw(" ")
#Html.LabelForModel(#Resources.LabelPeriodTo)
#Html.Raw(" ")
#Html.TextBox("periodTo", "", new { #class = "input-small" })
#Html.Raw(" ")
<input type="submit" class="btn" value="Filter" />
</p>
}
And controller for basic view with post-action Index, which fired when user press button:
public class IssuerDocumentsController : Controller
{
static readonly IEnumerable<IssuerDocument> Documents = DocumentsDAL.GetDocuments(1, 1).AsEnumerable();
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var documents = Documents.AsEnumerable();
// Check if document section filter is applied.
if (!string.IsNullOrEmpty(collection.Get("Sections")))
{
var documentSectionId = Convert.ToInt32(collection.Get("Sections"));
documents = documents.Where(d => d.SectionId == documentSectionId);
}
// Check if document type filter is applied.
if (!string.IsNullOrEmpty(collection.Get("Types")))
{
var documentTypeId = Convert.ToInt32(collection.Get("Types"));
documents = documents.Where(d => d.TypeId == documentTypeId);
}
return View(documents);
}
}

Categories

Resources