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)
Related
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"));
}
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);
}
}
});
}
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);
I have a view with a script (included below) that fires on a dropdownlist change, and the event handler should fill values for two text inputs. Values are received from controller.
The problem I'm having is, as soon as itemstatus list is populated, the controller returns back to view, and no values are passed back to AJAX function.
If I remove itemstatus list code and manually assign values as follows, it works:
var result = new { Quantity = "123", Price = "555"};
then it works.
I've also tried other ways to get data within controller but results were the same. Do you have any ideas what am I doing wrong and why controller returns back to view before "return Json"
<script type="text/javascript">
$(document).ready(function() {
//Dropdownlist Selectedchange event
$("#dropdown1").change(function ()
{
$("#txtQuantity").empty();
$("#txtPrice").empty();
$.ajax(
{
type: 'POST',
url: '#Url.Action("GetValues")',
dataType: 'json',
data: { id: $("#dropdown1").val() },
success: function(data)
{
$("#txtQuantity").val(data.Quantity);
$("#txtPrice").val(data.Price);
}
})
})
});
Controller:
public JsonResult GetValues(int id)
{
List<Item> itemstatus =
(from pd in db.Item
where (pd.itemID == id)
select new Item()
{
itemPrice = pd.itemPrice,
itemQuantity = pd.itemQuantity
}).ToList();
...
more code where i select what i need as a result i have two strings named itemquantity and itemprice
...
var result = new { Quantity= itemquantity, Price = itemprice };
return Json(result, JsonRequestBehavior.AllowGet);
}
because you are sending a list, whose data values can be accessed using
success: function(data)
{
$("#txtQuantity").val(data[0].Quantity);
$("#txtPrice").val(data[0].Price);
}