I have few drop-down list here as shown in , based on this drop-down selection next drop-down to it should be populated..
i tried to use this keyword to get value of current drop-down but i am unable to get it.
<td class="border-top-0 border-left-0 border-right-0 align-middle form-group">
#{
SelectList newSelectList = new SelectList((from s in Model.UserMasterList
.ToList()
select new
{
userId = s.userId,
userName = (s.userFirstName +' '+ s.userLastName)
}).Distinct()
,
"userId",
"userName",
string.IsNullOrEmpty(item.JobConstructionManagerId.ToString()) ? 0 : item.JobConstructionManagerId);
}
#Html.DropDownListFor(model => item.JobConstructionManagerId, (SelectList)newSelectList, new { #class = "form-control js-select js-noFilter hidden DDConstructionManager", size = "2", #value = 0, Id = "JobConstructionManager" + t ,#OnChange="fill();"}) //first dropdown
</td>
<td class="border-top-0 border-left-0 border-right-0 text-center text-align-center">
#{
SelectList newSelectStaffList = new SelectList((from s in Model.UserMasterStaffList //.UserConstructionManagersDetailList
.ToList()
select new
{
SuserId = s.userId, //s.conUserId,
SuserName = (s.userFirstName + ' ' + s.userLastName) //(s.mqUserMaster.userFirstName +' '+ s.mqUserMaster.userLastName)
}).Distinct()
,
"SuserId",
"SuserName",
string.IsNullOrEmpty(item.JobStaffId.ToString()) ? 0 : item.JobStaffId);
}
#Html.DropDownListFor(model => item.JobStaffId, (SelectList)newSelectStaffList, new { #class = "form-control js-select js-noFilter hidden DDStaff", size = "2", #value = 0, Id = "JobStaff" + t }) //second dropdown
</td>
main problem is that how to get just next drop-down to some particular drop-down
You must give an id attribute to your first dropdownlist then handle change event of dropdown with jquery to populate second dropdown.
<script type="text/javascript">
$('#firstDropDownId').change(function () {
$(function () {
$.ajax({
url: '#Url.Action("GetSecondData", "YourController")',
type: 'POST',
dataType: 'json',
data: { 'firstData': $("#firstDropDownId").val() },
success: function (data) {
var options = $('#secondDropDownId');
options.empty();
$.each(data, function (i, item) {
options.append($('<option />').val(item.Id).text(item.Display));
});
},
error: function (response) {
}
});
});
});
});
</script>
and then create an action method in your controller to populate second dropdown and return in json format.
[HttpPost]
public JsonResult GetSecondData(int firstId)
{
var result = ...; //populate result
return new JsonResult { Data = result };
}
In your first dropdown list, add another data-* attribute "cascade-list-id".
#Html.DropDownListFor(model => item.JobConstructionManagerId, (SelectList)newSelectList, new { #class = "form-control js-select js-noFilter hidden DDConstructionManager", size = "2", #value = 0, Id = "JobConstructionManager" + t ,#OnChange="fill();" "data-cascade-list-id"="newSelectStaffList" + t}) //first dropdown
In fill method, get the cascase list id, bind the new data with the id reference.
// pseudo code
function fill() {
var _that = this;
var cascadeId = $(_that).attr("data-cascade-list-id") // or use .data("cascadeListId");
// code to get the new data and binding, omitted for brevity
}
Hope this helps you..
I am giving you the country state example you can use this concept
<select name="country" id="country" onchange="states('state')">
<option value="">Select Country</option>
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
<option value="3">Algeria</option>
</select>
<select name="state" id="state">
<option value="">Select State</option>
function states(target){
var country = $("#country option:selected").val();
$.ajax({
type: "GET",
url: "url/"+country,
dataType: "text",
success: function(data){
if(data !=''){
$('#'+).html(data);
}
}
});
}
Related
How can make the autocomplete form return value in two different textbox? for example when select apple by using autocomplete form it will display "Apple" in textboxA and quantity "1" in textbox B.
I have tried the following code and succeeded to build the autocomplete form. But it show name in the selection and when select the item from list it will display value.
<script type="text/javascript">
$(document).ready(function () {
$("#CardName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/CardHolderDetails/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.CardName, value: item.CardId };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
<div class="form-group">
#Html.EditorFor(model => model.CardName, new { htmlAttributes = new { #class = "form-control", id = "CardName" } })
</div>
<div class="form-group">
#Html.EditorFor(model => model.CardId, new { htmlAttributes = new { #class = "form-control", id = "CardId" } })
</div>
[HttpPost]
public JsonResult Index(string Prefix)
{
List<CardHolderDetails> getCardList = new List<CardHolderDetails>();
getCardList = _service.getCardList();
List<CardHolderDetails> ObjList = new List<CardHolderDetails>();
foreach (var value in getCardList)
{
ObjList.Add(new CardHolderDetails { CardId = value.CardId, CardName = value.CardName });
}
//Searching records from list using LINQ query
var CardName= (from N in ObjList
where N.CardName.StartsWith(Prefix)
select new { N.CardName, N.CardId });
return Json(CardName, JsonRequestBehavior.AllowGet);
}
i expected when select the output from autocomplete form, the output CardName will be in textbox A and CardId in textbox B.
I tried to understand what the issue is exactly, but it's not clear - did you, or did you NOT get the autocomplete to work? Is it returning any meaningful value back to the client?
Anyways, with what we have here, it seems that there might be an issue with the Razor usage, probably with the way you're using the returned object:
<div class="form-group">
#Html.EditorFor(model => model.CardName, new { htmlAttributes = new { #class = "form-control", id = "CardName" } })
</div>
<div class="form-group">
#Html.EditorFor(model => model.CardId, new { htmlAttributes = new { #class = "form-control", id = "CardId" } })
</div>
From the model you're returning to the client and the Ajax script piece, I'd expect for the usage of the result 'model' object to look like this:
model => model.label and model => model.value.
Hello everybody I need to fix a cascading dropdownlist to work with Guid Id... It works ok with Int Id...but I need to work with Guid Id on my tables.
When I change the type to Guid (on my models and database)... It doesn't fill the dropdownlists
please help to solved this
I got this:
Controller
public JsonResult GetCountries()
{
return Json(countries.GetAll().ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetStatesByCountryId(string countryId)
{
//I know, I have to convert to Guid here... the problem is in the first dropdownlist
int Id = Convert.ToInt32(countryId);
var states = from s in state.GetAll() where s.CountryId == Id select s;
return Json(states);
}
View
<div>
#Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { #style = "width:250px;" })
</div>
<div style="margin-top:50px;">
#Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please select a state", new { #style = "width:250px;" })
</div>
</div>
<!-- jQuery -->
<script src="~/Assets/vendors/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="~/Assets/vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "GET",
url: "/Home/getcountries",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
//I think the problem is here it doesn't read Guid Numbers...when CountryId is a Guid
$('#dropdownCountry').append('<option value="' + value.CountryId + '">' + value.CountryName + '</option>');
});
}
});
$('#dropdownCountry').change(function () {
$('#dropdownState').empty();
$.ajax({
type: "POST",
url: "/Home/GetStatesByCountryId",
datatype: "Json",
data: { countryId: $('#dropdownCountry').val() },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownState').append('<option value="' + value.Id + '">' + value.StateName + '</option>');
});
}
});
});
});
</script>
If you change your type from Id in your entity model/db to Guid, the below line will fail
public JsonResult GetStatesByCountryId(string countryId)
{
int Id = Convert.ToInt32(countryId);
}
Convert.ToInt32 expects an object which can be converted to a valid int (Ex : "123"). But a Guid will be like "49e17a97-88ce-4acc-8aba-ae0c8740fd5d" and it cannot be converted to int. So just use Guid as your param.
public JsonResult GetStatesByCountryId(Guid countryId)
{
var states = (from s in state.GetAll() where s.CountryId == countryId
select s).ToList();
return Json(states, JsonRequestBehavior.AllowGet);
}
Assuming state.GetAll method returns a collection of item where it has a CountryId property of type Guid. (And the state's id's are also Guids)
I have a #Html.DropDownList on my view whose initial values are null. The values of the list must be populated based on the selected value from an other dropDownList. I have my two dropDownLists as below
<div class="col-sm-7">
#Html.DropDownList("City", null, new {#id="City", #class="form-control"})
</div>
<div class="col-sm-7">
#Html.DropDownList("Theatre", null, new {#id = "Theatre", #class = "form-control"})
</div>
Theatre must be populated based on the value selected in the dropDown list for city. As Theatre cannot be null, I initially set the ViewBag.Theatre to an empty list in my controller's action method. Once a city is selected, I am doing an ajax call from jQuery to call a different method in my controller to set the ViewBag.Theatre to my returned list.
But the contents of the Theatre dropDown are still empty. How do I refresh the contents of the dropDown after the ViewBag.Theatre value is changed?
Here is my jQuery to call the controller method
$("#City").change(function() {
if ($("#City").val() != 0) {
var ty = $("#City").val();
$.ajax({
url: rootDir + "/AnalysisHistory/SetTheatres",
data: {city: city },
type: "POST",
dataType: "html",
success: function () {
$(".form").show();
$("#loading").hide();
$("#analysisDetails").slideDown('slow');
});
} else {
$(".form").hide();
}
});
On change for the dropdown list for the city, here is what I did to populate the theaters drop down:
•I emptied the contents of the dropdown list for the theaters
•As I am receiving the new list as a JSON, on Success, I am re-populating the list with new contents. Here is my code
success: function (datax) {
var result = "";
var listObj = $.parseJSON(datax);
$(listObj).each(function (i, val) {
result += '<option value="' + val.Value + '">' + val.Text + '</option>';
});
$("#Theatre").html(result);
$(".form").show();
$("#loading").hide();
$("#analysisDetails").slideDown('slow');
}
I have dropdown list which was created dynamically like:
#for(int i=0;i<=count;i++)
{
#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { #class = "ddlProjectvalue" })
}
<input type="submit" value="Add Record" name="btn"/>
in Contoller I am loading data to dropdownlist:
[HttpPost]
Public ActionResult Timesheet()
{
TimsheetModel model=new TimesheetModel();
if(btn=="Add Record")
{
var data= Session["ddlData"] as IEnumerable<SelectListItem>;
SelectList list1=new SelectList(data,"Value","Text",model.ProjID);
ViewBag.ProjectList=list1;
count++; // ADDS NEW RECORD
return View();
}
else
{
var result = (from proj in db.PROJECTs where proj.IS_DELETED == "N" select new { Value = proj.ID, Text = proj.NAME })
SelectList list = new SelectList(result, "Value", "Text", tm.PROJ_ID);
ViewBag.ProjectList = list;//Data loaded here for Dropdown list
}
return View();
}
Now My Scenario is if count=5 which means if we have five dropdown lists, when I select item in first dropdown list should not show in second dropdown list and if we have select item in second dropownlist should not show items of first and second in third dropdown list. for that I have written script like:
<script>
$(document).ready(function () {
$('.ddlProjectvalue').change(function () {
var id = $('.ddlProjectvalue').attr('id');
var selector = "#" + id;
var selectedValue = $(this).val();
$.ajax({
url: "#Url.Action("GetDDLData","Employer")",
data: { selectedValue: selectedValue, id: id },
dataType: "json",
type: "GET",
error: function () {
alert(" An error occurred.");
},
success: function (data) {
debugger;
$("" + selector + "").removeClass("ddlProjectvalue");
$('.ddlProjectvalue').empty();
var optionhtml1 = '<option value="' +
0 + '">' + "--Choose a Project--" + '</option>';
$(".ddlProjectvalue").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data[i].Value + '">' + data[i].Text + '</option>';
$(".ddlProjectvalue").append(optionhtml);
});
}
});
});
});
</script>
and when i pass selected value to controller like:
public ActionResult GetDDLData(string selectedValue, string id, string addrecord)
{
int projectid = Convert.ToInt32(selectedValue);
if (id == "GetTimeSheetDetails_0__PROJ_ID")
{
IEnumerable<SelectListItem> projectslist = (from proj in db.PROJECTs where proj.IS_DELETED == "N" && proj.ID != projectid select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
var result = new SelectList(projectslist, "Value", "Text", tm.PROJ_ID).ToList();
Session["ddlData"] = result;
ViewBag.ProjectList = result;
return Json(result, JsonRequestBehavior.AllowGet);
}
else
{
var result = Session["ddlData"] as IEnumerable<SelectListItem>;
var query = (from data in result where data.Value != selectedValue select data) as IEnumerable<SelectListItem>;
Session["ddlData"] = query;
return Json(result, JsonRequestBehavior.AllowGet);
}
}
Now my problem is when I add new record by clciking on Add button, loading Session["ddldata"] data to total dropdown list instead it should remain selectlist item in first dropdownlist for first time, I need like when i first select a dropdownlist item in first dropdown list it should remain same when add record also. it means i should prevent server side load on first select list item and vice versa.
Note: Due to some issues i should add record on server side only
How I can prevent it, I tried like preventDefault or return false using jquery, but not working, Any Ideas? how can I fix it.
I think you are overcomplicating things here. You don't really need to request new options from server. Why not just filter the option out on the javascript side?
$(document).ready(function() {
$('.ddlProjectvalue').change(function() {
updateDDLValues();
});
updateDDLValues();
});
function updateDDLValues() {
// Display all
$('.ddlProjectvalue option').show();
// Hide all selected options from other selectlists
$('.ddlProjectvalue').each(function(i,element) {
var selectedvalue = $(element).find('option:selected').val();
$('.ddlProjectvalue').not(element).find('option[value="'+selectedvalue+'"]').hide();
});
}
Fiddle:
http://jsfiddle.net/Pt7qV/2/
Update:
As for the serverside part of your question, there are some serious flaws in your code. You increase the count property in your controller and use the variable clientside. First you'd think that's how it's done but nope it doesn't work that way.
You are returning View when Add Record is submitted but you aren't returning any model with it.
Your TimsheetModel would look something like this:
public class TimsheetModel
{
public int Count {get; set;}
}
In your controller you pass this to the view:
TimsheetModel model=new TimesheetModel();
if(btn=="Add Record")
{
var data= Session["ddlData"] as IEnumerable<SelectListItem>;
SelectList list1=new SelectList(data,"Value","Text",model.ProjID);
ViewBag.ProjectList=list1;
model.Count++; // ADDS NEW RECORD
return View(model);
}
And in your view:
#model TimsheetModel
#for(int i=0;i<=Model.Count;i++)
{
#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { #class = "ddlProjectvalue" })
}
<input type="submit" value="Add Record" name="btn"/>
I'd suggest you to go back to tutorials or books a bit, this is quite basic stuff after all. I won't go into how you are going to handle database side etc. since I think this answer would just escalate into explaining basic stuff.
I have 3 dropdownlist i wanna make 3 dropdownlist with cascade. I am using LinqSql for database..
I have 3 tables Product(id,name), Design(id,master_id,name), Model(id,design_id,name)
master_id bound to Product(id), design_id bound to Design(id)..
I want to create one dropdown which is gonna show Products and than when i choose a product its gonna make Design dropdown enabled else it will stay disabled.. also here is the tricky part that i couldnt solve and i need great explanation in here creating 3rd dropdown which is gonna be disabled normally till a Design is chosen.
Each of them gonna populate a lower dropdownlist bound to them.Its like;
Product gonna enable and populate Design,
Design gonna enable and populate Model.
I can do it with 2 dropdowns but when it comes to 3 dropdown i stuck really badly im on (brain-freeze)..
I already checked the other questions couldnt find any solution for my self. As i said im using LinqSql i need a solution about 3 cascadingdropdown list for this type of data reach.
thanks already for anything u can do! and if u can explain Model-View-Controller partials and the parameters and why you use them that would be awesome. Iam kinda beginner at this MVC3.
I would approach the problem something like this:
First, in the controller, we'll set up have the following methods:
public JsonResult GetDesignsForProduct(int productId)
{
// Instantiate our context and do whatever goo we need to select the objects we want
using (MyDatabaseContext ctx = new MyDatabaseContext())
{
return Json(ctx.Designs.Where(d => d.master_id == productId).ToList(), JsonRequestBehavior.AllowGet);
}
}
public JsonResult GetModelsForDesign(int designId)
{
// Instantiate our context and do whatever goo we need to select the objects we want
using (MyDatabaseContext ctx = new MyDatabaseContext())
{
return Json(ctx.Models.Where(d => d.design_id == designId).ToList(), JsonRequestBehavior.AllowGet);
}
}
I've turned on "get" here; if your data contains sensitive information - user names/e-mail addresses, other proprietary or legally protected data, etc. - you can change this to only allow "post", and modify your Javascript accordingly. See Phil Haack's article.
Also, if you expect this data to change frequently, these methods will cache it by default according to your application's cache settings. You can add an OutputCache attribute on the method to alter this behavior.
Then, in the view you'll have some AJAX plumbing, something like this:
function LoadDesigns() {
// Get the currently-selected value in our Product dropdown
var prod = $("#Product").val();
// Call our controller method and process the list of Design objects
$.getJSON('#Url.Content("~/ControllerName/GetDesignsForProduct")', { productId: prod },
function (designs) {
$("#Design").empty();
$.each(designs, function (i, c) {
$("#Design").append(
$('<option></option>').val(c.id).html(c.name)
);
});
});
}
function LoadModels() {
// Get the currently-selected value in our Design dropdown
var des = $("#Design").val();
// Call our controller method and process the list of Model objects
$.getJSON('#Url.Content("~/ControllerName/GetModelsForDesign")', { designId: des },
function (models) {
$("#Model").empty();
$.each(models, function (i, c) {
$("#Model").append(
$('<option></option>').val(c.id).html(c.name)
);
});
});
}
Finally, define all three drop-downs as follows:
#Html.DropDownList("Product", productSelectList, new { onchange = "LoadDesigns()" })
#Html.DropDownList("Design", null, new { onchange = "LoadModels()" })
#Html.DropDownList("Model")
Don't forget that the HTML helpers are really just shortcuts to generate the underlying HTML, and in Razor you frequently just go straight to HTML instead of messing with the helpers. So you could just as easily write these as:
<select id="Product" onchange="LoadDesigns()">
#foreach (var prod in products) {
<option value="#prod.id">#prod.name</option>
}
</select>
<select id="Design" onchange="LoadModels()"></select>
<select id="Model"></select>
Forget to set my finished work.. People may wanna see how it happens..
Here is my:
View + Jquery
$(function () {
$("select#Design").attr('disabled', 'true');
$("select#Model").attr('disabled', 'true');
$("select#Product").click(function () {
var prod = $("select#Product option:selected").val();
if (prod == "" || prod == 0) {
$("select#Design").attr('disabled', 'true');
$("select#Model").attr('disabled', 'true');
} else {
$.getJSON('#Url.Content("~/Admin/GetDesigns/")', { productId: prod }, function (data) {
$("select#Design").empty();
$("select#Model").empty();
$.each(data, function (i, c) {
$('select#Design').append('<option value="' + c.Value + '">' + c.Text + '</option>');
})
$("select#Design").removeAttr('disabled');
$("select#Design option:first").attr('selected', 'selected');
var des = $("select#Design option:selected").val();
if (des == "" || des == 0) {
$("select#Model").attr('disabled', 'true');
} else {
$.getJSON('#Url.Content("~/Admin/GetModels/")', { designId: des }, function (data) {
$("select#Model").empty();
$.each(data, function (i, c) {
$('select#Model').append('<option value="' + c.Value + '">' + c.Text + '</option>');
})
$("select#Model").removeAttr('disabled');
$("select#Model option:first").attr('selected', 'selected');
})
}
})
}
})
})
reason i use Jquery this way to fill all dropdowns and select first elements as default selection! When i choose an element from first dropdown the other two dropdowns starts to fill themselves and select their first element as default selection.. same code can be used for other dropdowns click function just like this:
$("select#Design").click(function () {
var des = $("select#Design option:selected").val();
if (des == "" || des == 0) {
$("select#Model").attr('disabled', 'true');
} else {
$.getJSON('#Url.Content("~/Admin/GetModels/")', { designId: des }, function (data) {
$("select#Model").empty();
$.each(data, function (i, c) {
$('select#Model').append('<option value="' + c.Value + '">' + c.Text + '</option>');
})
$("select#Model").removeAttr('disabled');
$("select#Model option:first").attr('selected', 'selected');
})
}
});
View
#using (Html.BeginForm("Index", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td style="background-color:#e8eef4;" rowspan="3">
</td>
<td style="width:190px; background-color:#e8eef4;">
#Html.DropDownList("Product", (SelectList)ViewData["ProductList"], "Please Select Product", new { style = "width:190px; padding:4px; margin:4px;" })
</td>
<td rowspan="3" style="width:400;">
</td>
<td style="background-color:#e8eef4;">
</td>
<td style="background-color:#e8eef4;" rowspan="3">
</td>
</tr>
<tr>
<td style="background-color:#e8eef4;">
<select id="Design" style="width:190px; padding:4px; margin:4px;">
<option label="Please Select Design" selected="selected"></option>
</select>
</td>
<td style="background-color:#e8eef4;">
</td>
</tr>
<tr>
<td style="background-color:#e8eef4;">
<select id="Model" style=" width:190px; padding:4px; margin:4px;">
<option label="Please Select Model"></option>
</select>
</td>
<td style="background-color:#e8eef4;">
</td>
</tr>
</table>
}
Just cause im using linqtosql and im too lazy to make a repository..
This is my CONTROLLER
public class AdminController : Controller
{
public linqVipDataContext db = new linqVipDataContext();
//
// GET: /Admin/
public ActionResult Index()
{
IEnumerable<SelectListItem> ProductItems = db.Products.AsEnumerable().Select(c => new SelectListItem()
{
Text = c.name,
Value = c.id.ToString(),
Selected = true,
});
SelectList prod = new SelectList(ProductItems, "Value", "Text");
ViewBag.ProductList = prod;
return View();
}
//
//Fill the Design List..
public JsonResult GetDesigns(int productId)
{
/*var data = dbs.Designs.Where(d => d.master_id == productId).ToList();*/
IEnumerable<SelectListItem> DesignItems = db.Designs.Where(c => c.master_id == productId).AsEnumerable().Select(c => new SelectListItem()
{
Text = c.name,
Value = c.id.ToString()
});
SelectList des = new SelectList(DesignItems, "Value", "Text");
return Json(des, JsonRequestBehavior.AllowGet);
}
//
//Fill the Model List..
public JsonResult GetModels(int designId)
{
/*This code down here! Doesnt work and says it's type is unknown*/
/*var data = dbs.Models.Where(d => d.design_id == designId).ToList();*/
/*For that reason im using this code*/
IEnumerable<SelectListItem> ModelItems = db.Models.Where(d => d.design_id == designId).AsEnumerable().Select(c => new SelectListItem()
{
Text = c.name,
Value = c.id.ToString()
});
SelectList mods= new SelectList(ModelItems, "Value", "Text");
return Json(mods, JsonRequestBehavior.AllowGet);
}
Json requires Value and Text 2 param seperated for creating a selectlist option.. So i must return my value that way..
I posted this cause i found some breakdowns at ur code, ty again for showing me this solution it gave me the idea and allowed me to solve all problems so this is the fully working code.. Ty again. Hope its usefull.