Add Autocomplete Address - c#

Add Autocomplete Address
I have a problem with the code.
No results found
I'm doing a job application form.
Controller
public JsonResult Getprovinces()
{
List<mydistrict> provincel = new List<mydistrict>();
provincel = (from p in _auc.mytable
select p).ToList();
return Json(provincel);
}
public JsonResult Getamphoes(int province_code)
{
List<mydistrict> amphoelist = new List<mydistrict>();
amphoelist = (from Provinces in _auc.mytable
where Provinces.province_code == province_code
select Provinces).ToList();
return Json(amphoelist);
}
public JsonResult Getdistrict(int province_code, string amphoe_code)
{
List<mydistrict> districtslist = new List<mydistrict>();
districtslist = (from district in _auc.mytable
where district.province_code == province_code
where district.amphoe_code == amphoe_code
select district).ToList();
return Json(districtslist);
}
public JsonResult detail(int province_code, string amphoe_code,string district_code)
{
List<mydistrict> detail = new List<mydistrict>();
detail = (from de in _auc.mytable
where de.province_code == province_code
where de.amphoe_code == amphoe_code
where de.district_code == district_code
select de).ToList();
return Json(detail);
}
view
<select id="mydistrict_province" onchange="showAmphoes()" class="form-control">
<option value=""></option>
</select><br />
<select id="mydistrict_amphoe" onchange="showDistricts()" class="form-control">
<option value=""></option>
</select><br />
<select id="mydistrict_district" onchange="showZipcode()" class="form-control">
<option value=""></option>
</select><br />
<input id="mydistrict_zipcode" class="form-control" />
script
$(document).ready(function () {
showProvinces();
});
function showProvinces() {
var url = '#Url.Content("~/")' + "Employee/Getprovinces";
var callback = function (result) {
$("#mydistrict_province").empty();
for (var i = 0; i < result.length; i++) {
$("#mydistrict_province").append(
$('<option></option>')
.attr("value", "" + result[i].province_code)
.html("" + result[i].province)
);
}
showAmphoes();
};
ajax(url, callback);
}
function showAmphoes() {
var province_code = $("#mydistrict_province").val();
var url = '#Url.Content("~/")' + "Employee/Getamphoes";
var callback = function (result) {
console.log(result);
$("#mydistrict_amphoe").empty();
for (var i = 0; i < result.length; i++) {
$("#mydistrict_amphoe").append(
$('<option></option>')
.attr("value", "" + result[i].amphoe_code)
.html("" + result[i].amphoe)
);
}
showDistricts();
};
ajax(url, callback);
}
function showDistricts() {
var province_code = $("#mydistrict_province").val();
var amphoe_code = $("#mydistrict_amphoe").val();
var url = '#Url.Content("~/")' + "Employee/Getdistrict";
var callback = function (result) {
$("#mydistrict_district").empty();
for (var i = 0; i < result.length; i++) {
$("#mydistrict_district").append(
$('<option></option>')
.attr("value", "" + result[i].district_code)
.html("" + result[i].district)
);
}
showZipcode();
};
ajax(url, callback);
}
function showZipcode() {
var province_code = $("#mydistrict_province").val();
var amphoe_code = $("#mydistrict_amphoe").val();
var district_code = $("#mydistrict_district").val();
var url = '#Url.Content("~/")' + "Employee/Getdetail";
var callback = function (result) {
for (var i = 0; i < result.length; i++) {
$("#mydistrict_zipcode").val(result[i].zipcode);
}
};
ajax(url, callback);
}
function ajax(url, callback) {
$.ajax({
"url": url,
"type": "GET",
"dataType": "json",
})
.done(callback);
}
Result
enter image description here
Help me please, Thanks

Your problem is that you don't send any parameter to your method so you can use below code to send parameter for showAmphoes:
var url = '#Url.Action("Getamphoes","Employee")' + '/?province_code=' + province_code;
and for showDistricts:
var url = '#Url.Action("Getdistrict", "Employee")' + '/?province_code=' + province_code + '&amphoe_code=' + amphoe_code;

Related

How do you move data from one cell in one row of a web grid to another cell in another row that is empty using jQuery?

I am kind of lost when it comes to jQuery sometimes, though I know there is a way! How do you update or move three cells data to another row based on the rows id to where the row is green (empty cells)? The row column ID name is "LocationID". MVC application using a web grid. What I am trying to do is when I check the row, use the drop-down that has the id, send the data to that row where the id exists populating the three empty cells in green with the current columnar data row that is checked. Any help would be greatly appreciated!
WebGrid below:
enter
<div id="content">
#webGrid.GetHtml(tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
//alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
htmlAttributes: new { #id = "webGrid" },
columns: webGrid.Columns(
webGrid.Column(header: "Actions", format:#<span class="link">
<!--Add Checkbox here-->
<!-- Note: We can add clickable rows as an option for user using a checkbox, one
selects the data move and the other move to selection. -->
#Html.CheckBoxFor(model => model.SelectedMoveIsChecked, new { #Class =
"SelectedMoveIsChecked", #id = "SelectedMoveIsChecked", #checked = false })
#Html.CheckBoxFor(model => model.SelectedMoveToChecked, new { #Class =
"SelectedMoveToChecked", #id = "SelectedMoveToChecked", #checked = false })
<!-- Html.CheckBox("isActive", false, item.isSelectdRow, true, new { id =
"CheckBoxSelectedBeginMove", Class = "CheckBoxIsSelected" })
Html.CheckBoxFor(Model.Input_Location, item.isSelectdRow, new { = "'SelectedRows'",
data_val = item.Location })
-->
<a class="Edit" href="javascript:;">Edit</a>
<a class="Clear" href="javascript:;">Clear</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
</span>),
webGrid.Column(header: "Location", format: #<div>
<label id="LocationLbl" class="label">#item.Location</label>
<input id="Location" class="text" type="text" value="#item.Location" style="display:none"
/><br />
#Html.DropDownListFor(model => model.LocationAppended, Model.LocationAppended,
"Section/Location", new { IReadOnlyDictionary = "document.forms[0].submit();", #id =
"RowLocationDropDownList", #class = "RowLocationDropDownList", #visibility = "hidden",
#placeholder = "Location" })
</div>, style: "Location"),
webGrid.Column(header: "Section", format: #<div>
<label id="SectionLbl" class="label">#item.Section</label>
<input id="Section" class="text" type="text" value="#item.Section" style="display:none" />
</div>, style: "Section"),
webGrid.Column(header: "TrailerNumber", format: #<div>
<label id="TrailerNumberLbl" class="label">#item.TrailerNumber</label>
<input id="TrailerNumber" class="text" type="text" value="#item.TrailerNumber"
style="display:none" />
</div>, style: "TrailerNumber"),
webGrid.Column(header: "CarrierName", format: #<div>
<label id="CarrierNameLbl" class="label">#item.CarrierName</label>
<input id="CarrierName" class="text" type="text" value="#item.CarrierName"
style="display:none" />
</div>, style: "CarrierName"),
webGrid.Column(header: "LoadCommodityStatus", format: #<div>
<label id="LoadCommodityStatusLbl" class="label">#item.LoadCommodityStatus</label>
<input id="LoadCommodityStatus" class="text" type="text" value="#item.LoadCommodityStatus"
style="display:none" />
</div>, style: "LoadCommodityStatus"),
webGrid.Column(header: "DateLoaded", format: #<div>
<label id="DateLoadedLbl" class="label">#item.DateLoaded</label>
<input id="DateLoaded" class="text" type="text" value="#item.DateLoaded" style="display:none"
/>
</div>, style: "DateLoaded"),
webGrid.Column(header: "UserName", format: #<div>
<label id="UserNameLbl" class="label">#item.UserName</label>
<input id="UserName" class="text" type="text" value="#item.UserName" style="display:none" />
</div>, style: "UserName"),
webGrid.Column(header: "PlantLocation", format: #<div>
<label id="PlantLocationLbl" class="label">#item.PlantLocation</label>
<input id="PlantLocation" class="text" type="text" value="#item.PlantLocation"
style="display:none" />
</div>, style: "PlantLocation"),
webGrid.Column(header: "RowPageID", format: #<div>
<label id="LocationIDLbl" class="label">#item.LocationID</label>
</div>, style: "LocationID"))),
<div id="RowCountBpttom"><b>Records: #firstRecord - #lastRecord of
#webGrid.TotalRowCount</b></div>
</div>
<br />
<div class="WebGridTable">
</div>
</div>
</form>
</div>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">
</script>
<script src="~/Scripts/YardDogAdmin.js"></script>
</body>
jQuery Below:
code here
enter
$('select.RowLocationDropDownList').attr('disabled', true);
$(".SelectedMoveIsChecked").change(function (i, row) {
$actualRowColorRed = $(row);
//When a value is selected in the dropdownlist box.
if ($(this).children("option:selected").val() != '') {
$("select.RowLocationDropDownList").change(function (i, row) {
$actualRowColorRed = $(row);
//Checks to see if the checkbox is checked, display the alert showing data and color the row red again.
/////// if ($('.SelectedMoveIsChecked').is(':checked') == true) {
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[0];
var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
var RowSection = ret[1];
var RowLocation = ret[2];
var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
// var ConfirmStr = " <b>Are you sure, you want to move this row From: </b>" + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
// alert("Alert " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?"
// );
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
if (confirm("Confirm! " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
confirm_value.value = "Yes";
//Add new values to (TrailerNumber, CarrierName, LoadCommodityStatus, DateLoaded, UserName).
//Note: Get the UserName currently using the Yard Dog Application.
/// $('#webGrid').closest('tr').find('#TrailerNumber').val();
/// $("#webGrid tbody tr").each(function (i, row) {
// $('#webGrid tbody tr').find('#LocationID'.val(RowLocationIDNum); //= RowLocationIDNum).append('#TrailerNumber'.val(CurrentRowTrailerNumber));
$("body").on("change", "select.RowLocationDropDownList", function () {
// $("body").on("click", "#webGrid TBODY .Update", function () {
// $("#content").on("click", "#webGrid INPUT", function () {
var row = $(this).closest("tr");
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
span.html(input.val());
}
});
//// $('#webGrid tbody tr').find('#LocationID').val(RowLocationIDNum) = customer;
var RowExchange = $(RowLocationID).closest("tr");
var ToRow = {};
ToRow.LocationID = row.find(".LocationID").find(".label").html();
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
/*
ToRow.LocationID = RowExchange.find('#LocationID').append(RowLocationID) ;
ToRow.UserName = RowExchange.find('.UserName').append(row.find(".UserName").find(".label").html());
ToRow.Location = RowExchange.find('.Location').append(row.find(".Location").find(".label").html());
ToRow.Section = RowExchange.find('.Section').append(row.find(".Section").find(".label").html());
ToRow.TrailerNumber = RowExchange.find('.TrailerNumber').append(ToRow.TrailerNumber);
ToRow.CarrierName = RowExchange.find('.CarrierName').val().append(ToRow.CarrierName);
ToRow.LoadCommodityStatus = RowExchange.find('.LoadCommodityStatus').append(ToRow.LoadCommodityStatus);
ToRow.DateLoaded = RowExchange.find('.DateLoaded').append(row.find(".DateLoaded").find(".label").html());
ToRow.PlantLocation = RowExchange.find('.PlantLocation').append(row.find(".PlantLocation").find(".label").html());
*/
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) +'}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 777);
});
}
else {
confirm_value.value = "Cancel";
}
document.forms[0].appendChild(confirm_value);
}
Confirm();
code here
Controller:
enter [HttpPost]
public ActionResult UpdateRowExchange(LocationData ToRow)
{
using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
{
LocationData updatedCustomer = (from c in entities.LocationDatas
where c.LocationID == ToRow.LocationID
select c).FirstOrDefault();
//Check for Duplicates.
///FindDuplicates(customer);
//HighlightDuplicate(webGrid);
//x => customer.TrailerNumber == x.TrailerNumber && x.TrailerNumber == customer.TrailerNumber //errases all data except the first cell TrailerNumber.
if (ToRow.UserName != null) updatedCustomer.UserName = ToRow.UserName.ToUpper();
else updatedCustomer.UserName = ToRow.UserName = null;
/*
if (customer.Location != null) updatedCustomer.Location = customer.Location.ToUpper();
else updatedCustomer.Location = customer.Location = null;
if (customer.Section != null) updatedCustomer.Section = customer.Section.ToUpper();
else updatedCustomer.Section = customer.Section = null;
*/
if (ToRow.TrailerNumber != null) updatedCustomer.TrailerNumber = ToRow.TrailerNumber.ToUpper();
else updatedCustomer.TrailerNumber = ToRow.TrailerNumber = null;
if (ToRow.CarrierName != null) updatedCustomer.CarrierName = ToRow.CarrierName.ToUpper();
else updatedCustomer.CarrierName = ToRow.CarrierName = null;
if (ToRow.LoadCommodityStatus != null) updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus.ToUpper();
else updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus = null;
if (ToRow.DateLoaded != null) updatedCustomer.DateLoaded = ToRow.DateLoaded.ToUpper();
else updatedCustomer.DateLoaded = ToRow.DateLoaded = null;
/*
if (customer.PlantLocation != null) updatedCustomer.PlantLocation = customer.PlantLocation.ToUpper();
else updatedCustomer.PlantLocation = customer.PlantLocation = null;
*/
//Create today's Date for a timestamp of inputs.
DateTime now = DateTime.Today;
ToRow.DateLoaded = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
updatedCustomer.DateLoaded = ToRow.DateLoaded;
entities.SaveChanges();
//Refresh(out, customer.ToString());
}
return new EmptyResult();
}
code here
Model below:
enter code here
namespace YardDog.Model
{
public class YardDogModel
{
ContYardDogAdmin ContYardDogData = new ContYardDogAdmin();
//Two Properties for DropDownList.
public List<LocationData> LocationDatas { get; set; }
//public List<LocationData> Location { get; set; }
public List<LocationData> TrailerNumber { get; set; }
public List<SelectListItem> PlantLocation { get; set; }
public List<SelectListItem> Location { get; set; }
public List<SelectListItem> LocationList { get; set; }
public List<SelectListItem> SectionList { get; set; }
public List<SelectListItem> LocationAppended { get; set; }
[Display(Name = "Name")]
public List<SelectListItem> Section { get; set; }
public List<SelectListItem> ListDuplicates { get; set; }
public List<SelectListItem> UserName { get; set; }
//Allow the data to be transfered (Backend into SQL Server).
[Required]
public string Input_Location { get; set; }
[Required]
public string Input_Section { get; set; }
public string Input_TrailerNumber { get; set; }
public string Input_CarrierName { get; set; }
public string Input_CommodityLoadStatus { get; set; }
[Required]
public string Input_PlantLocation { get; set; }
//YardDogModel YardDogDatas = new YardDogModel();
//string TrailerNumber = Input_TrailerNumber;
public bool SelectedMoveIsChecked { get; set; } = false;
public bool SelectedMoveToChecked { get; set; } = false;
public string LocationAppendedLbl { get; internal set; }
//public string LocationAppended { get; internal set; }
public string RowLocationDropDownList { get; set; }
public int RowLocationIDNum { get; set; }
}
}
JavaScript:
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[2];
var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
var RowSection = ret[0];
var RowLocation = ret[1];
var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
if (confirm("Confirm! " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
confirm_value.value = "Yes";
$("body").on("change", "select.RowLocationDropDownList", function () {
var row = $(this).closest("tr");
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
span.html(input.val());
}
});
//Tell the row change to be where ID exists by ID Number (RowLocationIDNum).
var ToRow = {};
ToRow.LocationID = RowLocationIDNum; //row.find(".LocationID").find(".label").html();
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
// setInterval('location.reload()', 777);
//Set the Clear Event to clear the initial rows.
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
$(this).find(".text").show();
$(this).find(".label").hide();
span.html(input.val(null));
span.show();
input.hide();
}
});
row.find(".Cancel").show();
row.find(".Clear").show();
row.find(".Edit").show();
$(this).hide();
var clear = {};
clear.LocationID = row.find(".LocationID").find(".label").html();
clear.UserName = row.find(".UserName").find(".label").html();
clear.Location = row.find(".Location").find(".label").html();
clear.Section = row.find(".Section").find(".label").html();
clear.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
clear.CarrierName = row.find(".CarrierName").find(".label").html();
clear.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
clear.DateLoaded = row.find(".DateLoaded").find(".label").html();
clear.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/ClearCustomer",
data: '{clear:' + JSON.stringify(clear) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 500);
});
}
else {
confirm_value.value = "Cancel";
setInterval('location.reload()', 500);
}
document.forms[0].appendChild(confirm_value);
}
Confirm();
});
}
});

MVC 5 Select list - user input

I am using the following to generate a dropdownlist of provinces based on the country selection:
<select id="Province" name="Province" class="form-control input-sm">
#{
string[] provinces = ViewBag.ProvincesForSelectedCountry;
string selectedProvinceName = null;
}
#{
if (Model != null && !String.IsNullOrEmpty(Model.Province))
{
selectedProvinceName = Model.Province;
}
else
{
selectedProvinceName = ConfigData.DefaultProvinceName;
}
}
#foreach (var anEntry in provinces)
{
string selectedTextMark = anEntry == selectedProvinceName
? "selected=\"selected\""
: String.Empty;
<option value="#(anEntry)" #(selectedTextMark)>#(anEntry)</option>
}
</select>
The challenge is I don't have a list of provinces (states) for other countries! Is there a way to allow for the user to type in the name of the province? Like a combobox.
I had to do it using Knockout-Kendo combobox, here is the solution:
Controller:
public ActionResult Index()
{
ViewBag.CountryID = new SelectList(db.Countries, "ID", "Name", "34");
.....
public JsonResult GetState(int? id)
{
if (id == null)
{ id = 34; }
var data = db.States.Where(x => x.CountryID == id)
.Select( x =>
new
{
ID = x.ID,
Name = x.Name
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
In the View:
#Html.DropDownList("Country", ViewBag.CountryID as SelectList, "Select...",
new { onchange = "UpdateProvinces();" })
<input data-bind="kendoComboBox: { dataTextField: 'Name', dataValueField: 'ID',
data: choices, value: selectedChoice }" />
Here is the JavaScript:
function UpdateProvinces() {
var countryId = $("#Country option:selected").val();
$.getJSON("/Home/GetState/" + countryId,
null,
function (data) {
objVM.choices(data);
});
}
function ItemViewModel(arg) {
arg = 34;
var self = this;
this.choices = ko.observableArray([]),
$.ajax({
type: "GET",
url: '#Url.Action("GetState", "Home")',
contentType: "application/json; charset=utf-8",
data: { id: arg },
dataType: "json",
success: function (data) {
self.choices(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
var selectedChoice = {
ID: self.ID,
Name: self.Name
};
self.selectedChoice = ko.observable();
}
var objVM = new ItemViewModel();
ko.applyBindings(objVM);
Edit:
Another alternative is to use Telerik MVC UI Combobox http://demos.telerik.com/aspnet-mvc/combobox/cascadingcombobox

Recover id in display list using combobox

i need to recover the id of element selected in combobox in dev express
and this is the code of combobox:
#Html.DevExpress().ComboBox(
settings =>
{
settings.Name = "comboBox4";
settings.Width = 180;
settings.SelectedIndex = 0;
settings.Properties.DropDownWidth = 550;
settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
settings.CallbackRouteValues = new { Controller = "Editors", Action = "MultiColumnComboBoxPartial" };
settings.Properties.CallbackPageSize = 30;
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
settings.Properties.TextFormatString = "{1}";
settings.Properties.ValueField = "Id";
settings.Properties.ValueType = typeof(string);
settings.Properties.Columns.Add("Id", "Id", 130).SetColVisible(false);
// settings.Properties.Columns.Add("Id", "Id", 130).SetColVisibleIndex(1);
settings.Properties.Columns.Add("Nom", "Nom", 130);
settings.Properties.Columns.Add("Prenom", "Prenom", Unit.Percentage(100));
settings.Properties.Columns.Add("DateNaissance", "DateNaissance", 60);
settings.Properties.Columns.Add("CodeClient", "CodeClient", 100);
}
).BindList(client).GetHtml()
and this the method ajax how i put the value of any custom with ajax:
function Addprojet() {
debugger;
var nom = $("#nom2_I").val();
var description = $("#Description_I").val();
var client = $("#comboBox4_I").val();
var chef = $("#chefid_I").val();
var complexite = $("#comboBox1_I").val();
var taille = $("#comboBox2_I").val();
var datedebut = $("#datedebut_I").val();
$.ajax({
url: "/Projet/AjouterProjet?nom=" + nom + "&description=" + description + "&client=" + client + "&chef=" + chef + "&complexite=" + complexite + "&taille=" + taille + "&datedebut=" + datedebut, // /Controlleur/Action
type: "POST",
dataType: 'text',
//data : {Nom: nom},
success: function (responseText) {
debugger;
if (responseText == "True") {
location.replace("/Client/listeclients");
}
else {
alert("error");
}
}
});
}
</script>
how can i resolve this issue because i need to recover the id of client without displaying in the list in the combobox
can semeone help me to fix it .

Passing response from ajax call to view in C#

I am using ajax to call an action in the controller. The code is like this
$('#kitchen').change(function () {
var selectedKitchen = $('#kitchen').val();
if (selectedKitchen != '') {
console.log("selected item:" + $('#kitchen').val());
$.ajax({
type: "GET",
url: "/Home/GiveInsitutionsWithoutResponsibility",
data: "id=" + selectedKitchen,
dataType:'json',
success: function (result) {
result = JSON.parse(result);
console.log(result.length);
},
error: function (error) {
console.log("There was an error posting the data to the server: ");
console.log(error.responseText);
}
});
}
});
Now what I want is to use the result coming from the server to populate a drop down on the client side. How should I do it? Is there a way for it or my approach here is wrong?
My result object is like this
{
Id: "04409314-ea61-4367-8eee-2b5faf87e592"
Name: "Test Institution Two"
NextPatientId: 1
OwnerId: "1"
PartitionKey: "1"
RowKey: "04409314-ea61-4367-8eee-2b5faf87e592"
Timestamp: "/Date(1417180677580)/"
}
The controller function is like this
public ActionResult GiveInsitutionsWithoutResponsibility()
{
var kitchenId = Request["id"].ToString();
Kitchen k = Kitchen.Get(kitchenId);
IEnumerable <Institution> ins = k.GetInstitutions();
IEnumerable<Institution> allIns = Institution.GetAll();
List<Institution> result = new List<Institution>();
bool contain = true;
int index = 0;
if (ins.Count() > 0)
{
for (int i = 0; i < allIns.Count(); i++, contain = true)
{
for (int j = 0; j < ins.Count(); j++)
{
if (allIns.ElementAt(i).Id == ins.ElementAt(j).Id)
{
contain = true;
break;
}
else
{
index = j;
contain = false;
}
}
if (!contain)
{
result.Add(allIns.ElementAt(index));
}
}
}
else
{
for (int i = 0; i < allIns.Count(); i++)
{
result.Add(allIns.ElementAt(index));
}
}
string response = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(result);
return Json(response, JsonRequestBehavior.AllowGet);
}
First your action method can be simplified to
public ActionResult GiveInsitutionsWithoutResponsibility(int ID)
{
Kitchen k = Kitchen.Get(ID);
var data = Institution.GetAll().Except(k.GetInstitutions(), new InstitutionComparer()).Select(i => new
{
ID = i.ID,
Name = r.Name
});
return Json(data, JsonRequestBehavior.AllowGet);
}
Note the Kitchen.ID is passed in the method parameter. The Linq query is used to select all Institution's then exclude any Institution's that already exist in the Kitchen, then creates a collections of anonymous object so unnecessary data is not sent to the client. The Json() method returns the data in the correct JSON format (calling JavaScriptSerializer().Serialize() is not required).
In order for .Except() to work with complex objects, you need a comparer
public class InstitutionComparer : IEqualityComparer<Institution>
{
public bool Equals(Institution x, Institution y)
{
if (Object.ReferenceEquals(x, y))
{
return true;
}
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
{
return false;
}
return x.ID == y.ID;
}
public int GetHashCode(Institution institution)
{
if (Object.ReferenceEquals(institution, null))
{
return 0;
}
return institution.ID.GetHashCode();
}
}
Next change the ajax method to
$('#kitchen').change(function () {
var selectedKitchen = $('#kitchen').val();
if (!selectedKitchen) {
return;
}
$.ajax({
type: "GET",
url: '#Url.Action("GiveInsitutionsWithoutResponsibility", "Home")', // don't hard code urls
data: { id: selectedKitchen }, // pass selectedKitchen to the id parameter
dataType:'json',
success: function (result) {
var select = $('YourDropDownSelector').empty().append($('<option></option>').val('').text('--Please select--'));
$.each(result, function(index, item) {
select.append($('<option></option>').val(item.ID).text(item.Name));
});
},
error: function (error) {
}
});
});
or you could use the short cut
$.getJSON('#Url.Action("GiveInsitutionsWithoutResponsibility", "Home")', { id: selectedKitchen }, function(result) {
$.each(result, .... // as above
});
Depending on the object from your controller, you could loop through your results data and .append this to your drop down list.
success: function (result) {
$.each(result, function(index, manager) {
$('select#yourId').append(
'<option value="' + result.Id + '">'
+ result.Name +
'</option>');
});
}
Your approach is fine, you will have to format the result to be added to combo box. For example, support on a page I have country and states combo box. Based on selected country, I need to populate state, so I will write following code:
$("#billingContactCountry").change(function (e) {
e.preventDefault();
var countryId = $("#billingContactCountry").val();
getStatesByCountry(countryId, "", "#billingContactState", "#billingContactZip");
});
function getStatesByCountry(countryId, stateId, stateCombobox, zipTextBox) {
$.ajax({
url: "#Url.Action("GetStatesByCountry", "Admin")",
data: { countryId: countryId },
dataType: "json",
type: "GET",
error: function (xhr, status) {
//debugger;
var items = "<option value=\"\">-Select State-</option>";
$(stateCombobox).html(items);
var zipMessage = validateZip(countryId, $(zipTextBox).val());
if (zipMessage != "The ZIP Code field is required.") {
$(zipTextBox).parent().find("span.field-validation-error").text(zipMessage);
}
$("div.overlay").hide();
},
success: function (data) {
//debugger;
var items = "<option value=\"\">-Select State-</option>";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Id + "\">" + item.Name + "</option>";
});
$(stateCombobox).html(items);
if (stateId != "") {
$('#billingContactState').val(stateId);
}
var zipMessage = validateZip(countryId, $(zipTextBox).val());
if (zipMessage != "The ZIP Code field is required.") {
$(zipTextBox).parent().find("span.field-validation-error").text(zipMessage);
}
$("div.overlay").hide();
}
});
}
So basically interesting code is,
var items = "<option value=\"\">-Select State-</option>";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Id + "\">" + item.Name + "</option>";
});
$(stateCombobox).html(items);
We are operating on each element returned from server to create option item for combo box.
As an aside, you should use #Url.Action as shown in example above.

Ajax call not reach to server side methods?

When i click on button it will call JavaScript method after that on Ajax call if i debug it on Firefox browser than it calls server side method setMandate() but not directly on button click, i don't know what is happening?
<div>
<button id="GetMandateBtn" onclick="SetMandate()" disabled>Get Mandate</button>
</div>
function SetMandate() {
var clients = new Array();
var queryNo = 0;
$("#DivMandateClients input:checked").each(function () {
clients.push($(this).attr('value'));
});
if (clients == "")
clients.push(0);
var contacts = new Array();
$("#DivMandateClientsContact input:checked").each(function () {
contacts.push($(this).attr('value'));
var value = $(this).val();
});
if (contacts == "")
contacts.push(0);
var candidateStatus = new Array();
$("#candidateStatus input:checked").each(function () {
candidateStatus.push($(this).attr('value'));
});
if (candidateStatus == "") {
candidateStatus.push(0);
queryNo = 0;
}
var mandateRegion = new Array();
$("#MandateRegion input:checked").each(function () {
mandateRegion.push($(this).attr('value'));
});
if (mandateRegion == "") {
mandateRegion.push(0);
queryNo = 0;
}
var mandateCountry = new Array();
$("#MandateCountry input:checked").each(function () {
mandateCountry.push($(this).attr('value'));
});
if (mandateCountry == "") {
mandateCountry.push(0);
queryNo = 0;
}
var researchers = new Array();
$("#Researcher input:checked").each(function () {
researchers.push($(this).attr('value'));
});
if (researchers == "") {
researchers.push(0);
queryNo = 0;
}
if (StartDateTxt.value.trim() != "" && EndDateTxt.value.trim() != "") {
$.ajax({
url: "/WebService/GetMandate",
data: "{ 'startDate' : '" + StartDateTxt.value + "','endDate' : '" + EndDateTxt.value + "','clients' : '" + clients + "','contacts' : '" + contacts + "','candidateStatus' : '" + candidateStatus + "','mandateRegion' : '" + mandateRegion + "','mandateCountry' : '" + mandateCountry + "','researchers' : '" + researchers + "','queryNo' : '" + queryNo + "'}",
dataType: "json",
type: "POST",
dataFilter: function (data) { return data; },
success: function (data) {
var mandate = $("#Mandate");
mandate.html("");
if (data != null) {
if (data != "")
mandate.append($("<input type='checkbox' id='chklstMandate-2' name='Mandate' value='-2'/> <label style='display:inline;' id='lblMandate-2'>Select All</label><hr/>"));
$.each(data, function (index, value) {
mandate.append($("<input type='checkbox' id='chklstMandate" + data[index].ResearcherId + "' name='Mandate' value='" + data[index].ResearcherId + "'/> <label style='display:inline;' id='lblMandate" + data[index].ResearcherId + "'>" + data[index].MandaName + "</label><br />"));
});
$("#chklstMandate-2").click(function (event) {
if ($("#chklstMandate-2").is(":checked"))
$("#Mandate").each(function () {
$("input[type=checkbox][name='Mandate']").attr("checked", true);
});
else if ($("#chklstMandate-2").not(":checked"))
$("#Mandate").each(function () {
$("input[type=checkbox][name='Mandate']").attr("checked", false);
});
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error on Loading Mandate" + errorThrown);
}
});
}
};
public ActionResult GetMandate()
{
// InputStream contains the JSON object you've sent
String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();
// Deserialize it to a dictionary
var dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<String, string>>(jsonString);
var startDate = Convert.ToDateTime(dic["startDate"]);//DateTime.Parse(dic["startDate"]);
var endDate = DateTime.Parse(dic["endDate"]);
string[] clients = dic["clients"].Split(',');
string[] contacts = dic["contacts"].Split(',');
string[] candidateStatus = dic["candidateStatus"].Split(',');
string[] mandateRegion = dic["mandateRegion"].Split(',');
string[] mandateCountry = dic["mandateCountry"].Split(',');
string[] researchers = dic["researchers"].Split(',');
int queryNo = int.Parse(dic["queryNo"]);
//bool isClientIdSelected = true;
List<int> clientIds = new List<int>();
foreach (var clnt in clients)
{
if (clnt != "-2" && clnt != "0")
clientIds.Add(int.Parse(clnt));
}
List<int> contactIds = new List<int>();
foreach (var conts in contacts)
{
if (conts != "-2" && conts != "0")
contactIds.Add(int.Parse(conts));
}
List<int> candidateStatusIds = new List<int>();
foreach (var status in candidateStatus)
{
if (status != "-2" && status != "0")
candidateStatusIds.Add(int.Parse(status));
}
List<int> mandateRegionIds = new List<int>();
foreach (var region in mandateRegion)
{
if (region != "-2" && region != "0")
mandateRegionIds.Add(int.Parse(region));
}
List<int> mandateCountryIds = new List<int>();
foreach (var country in mandateCountry)
{
if (country != "-2" && country != "0")
mandateCountryIds.Add(int.Parse(country));
}
List<int> researcherIds = new List<int>();
foreach (var researcher in researchers)
{
if (researcher != "-2" && researcher != "0")
researcherIds.Add(int.Parse(researcher));
}
if (queryNo == 0)
{
var mandaetFromDB = (from mc in dbContext.MandateCandidates
join m in dbContext.Mandates on mc.MandateId equals m.MandateId
join mr in dbContext.MandateResearchers on mc.MandateId equals mr.MandateId
where m.StartDate >= startDate
&& m.EndDate <= endDate
&& clientIds.Contains(m.ClientId)
&& contactIds.Contains(m.ContactId)
&& candidateStatusIds.Contains(mc.CandidateStatusId ?? 0)
select new { MandateId = m.MandateId, MandaName = m.Name, ResearcherId = mr.ResearcherId, ClientId = m.ClientId }).ToList();
return Json(mandaetFromDB, JsonRequestBehavior.AllowGet);
}
else
{
var mandaetFromDB = (from mc in dbContext.MandateCandidates
join m in dbContext.Mandates on mc.MandateId equals m.MandateId
join mr in dbContext.MandateResearchers on mc.MandateId equals mr.MandateId
where m.StartDate >= startDate
&& m.EndDate <= endDate
&& clientIds.Contains(m.ClientId)
&& contactIds.Contains(m.ContactId)
&& candidateStatusIds.Contains(mc.CandidateStatusId ?? 0)
&& mandateRegionIds.Contains(m.RegionId ?? 0)
&& mandateCountryIds.Contains(m.MandateCountryId ?? 0)
&& researcherIds.Contains(mr.ResearcherId ?? 0)
select new { MandateId = m.MandateId, MandaName = m.Name, ResearcherId = mr.ResearcherId, ClientId = m.ClientId }).ToList();
return Json(mandaetFromDB, JsonRequestBehavior.AllowGet);
}
//return Json(mandaetFromDB, JsonRequestBehavior.AllowGet);
}

Categories

Resources