I have the following model :
Trucktype
ID
Description
List of ModelCodes
ModelCodes
Id
Code
Now I want to create a page which has two dropdowns one for the TruckType and one for the ModelCode so that I can display the trucks that correspond to the selection.
I can fill the first one, but how do I fill the second dropdown once you selected a value in the first dropdown?
Consider dropdownlist1 the one which will filter the results in dropdownlist2 and adapt to your db schema and context, obviously.
$("#dropdownlist1_ID").change(function() {
$.ajax({
type: 'POST',
url: 'GetValuesForDropdownlist2',
dataType: 'json',
data: { id: $("#dropdownlist1_ID").val() },
success: function (data) {
$.each(data, function (i, item) {
$("#dropdownlist2_ID").append('<option value="' + item.Value + '">' + item.Text + '</option>');
});
},
error: function (ex) {
console.log('Failed to retrieve data. Exception: ' + ex);
}
});
});
In the controller something like:
public JsonResult GetValuesForDropdownlist2(int id)
{
var selected = db.dropdownlist1_Table.Where(t => t.Id == id).FirstOrDefault();
return Json(new SelectList(db.dropdownlist2_Table.Where(t => (t.Column_To_Filter == selected.Id)), "Column_ID", "Column_Description"));
}
Related
Hopefully an easy one to answer. I am using the code below to produce a cascading dropdown, however when I select the Country, the State auto populates with the first value (for the appropriate Country) in my State table. I think that I need to add an empty string somewhere but I'm not sure where.
Thanks
h2>Cascading DropDownList Sample</h2>
<div>
<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>
#section scripts
{
<script>
$(function () {
$.ajax({
type: "GET",
url: "/test/getcountries",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCountry').append('<option value="' + value.CountryId + '">' + value.CountryName +'</option>');
});
}
});
$('#dropdownCountry').change(function () {
$('#dropdownState').empty();
$.ajax({
type: "POST",
url: "/test/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>
}
In your country drop down change event success call back function you have to make one line of change.
$('#dropdownState').append('<option>Select State</option>');
$.each(data, function (index, value) {
$('#dropdownState').append('<option value ="' +
value.Id + '">' + value.StateName + '</option>');
});
And I suggest you put your options in variable and finally assign that value to drop down.
var html = '';
html = '<option>Select State</option>';
$.each(data, function (index, value) {
html += '<option value ="' +
value.Id + '">' + value.StateName + '</option>';
});
$('#dropdownState').html(html)
append function add options to select element which will cause problem like if you select country A which will provide 5 states. Then you select country B which provides 10 states then final result in states drop down will be 15 states option for country B. Thus instead of append I have used html function.
You can just add a mock item in the first place of the elements returned by the service GetStatesByCountryId. The id field can be blank and the statename can be something like "Please Choose". Then, you can check if the selected item id is blank or not.
application in MVC fraework.
from list of employee grid when user click on Edit button particular employee data would get display in the page. i have added one autocomplete textbox for users
i want to set autocomplete value based on clicked employee data.
$("#autoAssginedTo").autocomplete({
source: function (request, response) {
$.ajax({
url: "/LeadGeneration/GetUsers",
type: "GET",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.FirstName + ' ' + item.LastName, value: item.FirstName + ' ' + item.LastName, val: item.ID };
}))
}
})
},
messages: {
noResults: "", results: ""
},
select: function (e, i) {
$("#AssignedTo").val(i.item.val);
},
});
i tried following :
function setAutocompletCurrentValue(id, value) {
$(id).val(value);
var textToShow = $(id).find(":selected").text();
$(id).parent().find("span").find("input").val(textToShow);
}
but it sets id of user. i want to set employee name associated with empId
how to do that ?
Instead of this:
$("#AssignedTo").val(i.item.val);
Replace it with this one:
$("#AssignedTo").val(i.item.label);
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 to create auto complete text box in my web form for the below condition
if i type country name then the auto complete suggestion should show the list of countries,state and city name which are stored in my database.
if i type city name then the auto suggestion should show the country and statename from my database,similarly statename also
For Example : if the user type
tamilnadu
then the result will be
tamilnadu, India
if the user type chennai in text box
then the auto complete suggestion should be
chennai,tamilnadu, india
if the user type Erode tamilnadu
then the result should be
Erode,tamilnadu,india
i have use different tables for each values like city, state, and country
all i have done till now is ive a textbox which shows only city search
My question is how can i achieve the result as i mentioned above like mulitple entries input to the textbox and multiple suggestion as a output like google place search
pls guide me i've search all over the web but i cant find the perfect solution
Here is my code for script
<script type ="text/javascript" >
$(function () {
$('#<%=txtSearch.ClientID%>').autocomplete({
source: function (request, response) {
$.ajax({
url: "Default.aspx\getCityName",
data: "{'pre':'" + request.term + "'} ",
datatype: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
cityname: item.cityname,
country: item.country,
json: item
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
focus: function (event, ui) {
$('#<%=txtSearch.ClientID%>').val(ui.item.cityname);
return false;
},
select: function (event, ui) {
$('#<%=txtSearch.ClientID%>').val(ui.item.citycame);
return false;
}
}).data("ui.autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>City:" + item.cityname + "<br>Country :" + item.country + "</a>")
.appendTo(ul);
};
});
</script>
Code of my webservice :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Searchcity> getCityName(String pre)
{
List<Searchcity> allcity = new List<Searchcity>();
using(MydatabaseEntities dc = new MydatabaseEntities())
{
allcity = (from a in dc.Searchcities
where a.cityname.StartsWith(pre)
select a).ToList();
}
return allcity;
}
This may help you!
AJAX
var Autoarr = [];
$.ajax({
url: "',
dataType: "json",
async: false,
success: function (data) {
var result = $.map(data, function (val, key) {
return { type: key, cityname: val.cityname, country: val.country};
});
for (var i = 0; i < result.length; i++) {
Autoarr[i] = result[i].cityname;
}
}
});
AUTOCOMPLETE
$(function () {
$("#category").autocomplete({
source: Autoarr
});
});
You have to write SQL query with selection of 3 coloumns. 1> Country 2> State 3> City. SQL query should have 3 conditions.
Like below
if(select count(1) from Table where cityname like "#cityname")
begin
select city,state,country from table
end
else if(select count(1) from Table where state like "#statename")
begin
select 1 as city, state,country from table
end
else if(select count(1) from Table where country like "#countryname")
begin
select 1 as city, 1 as state, country from table
end
Please get this value in json using ajax.
Then append every each column with ',' seperator for example(Chennai,Tamilnadu,India).
If any coloumn value is 1 then omit it. for example
(1,Tamilnadu,India then omit 1. so Tamilnadu,India). You need to think more with this example. If you have different tables then use joins.
Is it possible for me to get the same SelectListItems in this list:
public static List<SelectListItem> GetAreaApprovingAuthorities(int id)
{
List<Employee> approvingAuthorities = new List<Employee>();
using (var db = new TLMS_DBContext())
{
approvingAuthorities = db.Employees.Where(e => e.UserRoleID > 1 && e.PersonnelAreaID == id).ToList();
}
List<SelectListItem> returned = new List<SelectListItem>();
foreach (Employee emp in approvingAuthorities)
{
returned.Add(new SelectListItem { Text = string.Format("{0} {1}", emp.FirstName, emp.LastName), Value = emp.ID.ToString() });
}
return returned;
}
and pass them into a select list using Json?
Here is the controller action where the List is acquired:
public JsonResult GetApprovingAuthorities(int id)
{
return Json(TLMS_DropDownLists.GetAreaApprovingAuthorities(id),JsonRequestBehavior.AllowGet);
}
Here is where the json object is iterated through and then passed to the select list (this is triggered when another select list's value is changed):
$.ajax({
type: 'GET',
data: { id: selectedValue },
url: '#Url.Action("GetApprovingAuthorities")',
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
success: function (jsonObj) {
$('#aa').empty();
$.each(jsonObj, function (key, value) {
$('#aa').append($("<option/>", {
value: key.Text,
text: value.Text
}));
});
}
});
This is working to populate the "aa" select list and I am receiving the select list's selected item via the FormCollection in a controller action, but I cannot capture the original ID from the "GetAreaApprovingAuthorities" SelectListItem's Value. Is there a way that I can make this happen?
When you're iterating on the jsonObj it should be like this
//the first parameter is just the index of the iteration
//and the second one is the json object (SelectListItem)
$.each(jsonObj, function (index, obj) {
$('#aa').append($("<option/>",
{
value: obj.Value,
text: obj.Text
}));
});