What is the best way to pass a LINQ value into J-Query???... How would I go about this?
When the Update link is clicked, it checks the web Grid to see if it is the same on TrailerNumber and CarrierName. If the inputs are the same in both fields as already existing, then allows you to move the data to the current row. (avoid duplication)
Any help would be greatly appreciated!
Checks to see is the inputs already exist in TrailerNumber and CarrierName as the same.
LINQ (Controller):
bool AlreadyInTable = entities.LocationDataMasters.Any(t => t.TrailerNumber == customer.TrailerNumber && t.CarrierName == customer.CarrierName);
//Update event handler.
$("body").on("click", "#webGrid TBODY .Update", function () {
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");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Cancel").hide();
row.find(".Clear").show();
$(this).hide();
var customer = {};
customer.LocationID = row.find(".LocationID").find(".label").html();
customer.UserName = row.find(".UserName").find(".label").html();
customer.Location = row.find(".Location").find(".label").html();
customer.Section = row.find(".Section").find(".label").html();
customer.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
customer.CarrierName = row.find(".CarrierName").find(".label").html();
customer.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
customer.DateLoaded = row.find(".DateLoaded").find(".label").html();
customer.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}) //setInterval('location.reload()', 777);
/*************************** Added to Find Duplicates ******************************/
/***********************************************************************************/
/***********************************************************************************/
//(1)Finds the Current Row selected with Edit Link:
var CurrentLocationID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentLocation = $(this).closest('tr').find("#LocationLbl").text();
var CurrentSection = $(this).closest('tr').find("#SectionLbl").text();
var CurrentTrailerNumber = $(this).closest('tr').find("#TrailerNumberLbl").text();
var CurrentTrailerNumberVal = $(this).closest('tr').find("#TrailerNumber").val();
var CurrentCarrrierNameLbl = $(this).closest('tr').find("#CarrierNameLbl").text();
var CurrentCarrrierName = $(this).closest('tr').find("#CarrierName").val();
var CurrLocationID = $(this).closest('tr').find("#LocationID").val();
var CurrentIDTrailerCarrier = 'Current Row Location, LocationID: ' + CurrentLocationID + ' Location: ' + CurrentLocation + ' Section: ' + CurrentSection + ' TrailerNumber: ' + CurrentTrailerNumber + ' CarrierName: ' + CurrentCarrrierName;
var TrailerNumberRows = $('#webGrid tr').find("#TrailerNumber").val();
//Identify the current row data to find duplicates against.
/// alert("CurrentIDTrailerCarrier: " + CurrentIDTrailerCarrier);
// $('#webGrid TR').each(function (row, x) {
//=========== This decision is what determines to check for duplicates. ==============
//Loop through Rows that contain the same Trailer Number and Count Rows:
var TrailerNumberContainsCount = $("#webGrid tr > td #TrailerNumberLbl:contains('" + CurrentTrailerNumber + "')").parent().length;
var CarrierNameContainsCount = $("#webGrid tr > td.CarrierName:contains('" + CurrentCarrrierNameLbl + "')").parent().length;
/// alert("TrailerNumberContainsCount: " + TrailerNumberContainsCount + " CarrierNameContainsCount: " + CarrierNameContainsCount);
**if (TrailerNumberContainsCount > 1 && $("#webGrid tr > td #TrailerNumberLbl:contains('" + CurrentTrailerNumber + "')") && $("#webGrid tr > td.CarrierName:contains('" + CurrentCarrrierNameLbl + "')") && CarrierNameContainsCount > 1 ) {**
/****************************************************************/
/************** Find Duplicates Get the LocationID **************/
/****************************************************************/
//Hide rows on TrailerNumber & CarrierName that don't match.
$("#webGrid tr > td #TrailerNumberLbl:not(:contains('" + CurrentTrailerNumber + "'))").filter(':visible').parents().closest('TR').hide();
$("#webGrid tr > td #CarrierNameLbl:not(:contains('" + CurrentCarrrierNameLbl + "'))").filter(':visible').parent().closest('TR').hide(); //Hide Rows that don't contain value.
//Take out the ID that is on the current row to show the duplicate ID only.
var DuplicateID = $('#webGrid tr').filter(':visible').find("#LocationIDLbl:not(:contains('" + CurrentLocationID + "'))").text();
DuplicatesVisibleID = DuplicateID;
//Call the DuplicateID Row to be colored Yellow where the duplicate exists:
$("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible').attr('style', 'background-color:#FFFF00;');
$('#webGrid tr:first').parent().show(); //Always show the header.
/********************************************************/
/****************** Start Selection *********************/
/********************************************************/
///$('.SelectedMoveToChecked').attr('disabled', true);
//Allow only one selection of the row to be checked on a checkbox.
$('.SelectedMoveToChecked').click('td', function () {
$(".SelectedMoveIsChecked").not(this).prop('checked', false);
$(".SelectedMoveToChecked").not(this).prop('checked', false);
});
//$(this).closest('tr').find('.RowLocationDupDropDownList').removeAttr('disabled');
$(".SelectedMoveIsChecked").filter(':visible').hide();
$(this).closest("tr").find(".SelectedMoveToChecked").show();
//$('.RowLocationDupDropDownList').hide();
//Gather the data from the row that has the LocationID that is the Duplicate.
var DupRow = $("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible');
var DupLocation = DupRow.find('#LocationLbl').text();
var DupSection = DupRow.find('#SectionLbl').text();
var DupTrailerNumber = DupRow.find('#TrailerNumberLbl').text();
var DupCarrierName = DupRow.find('#CarrierNameLbl').text();
var DupLoadCommodityStatus = DupRow.find('#LoadCommodityStatusLbl').text();
var DupDateLoaded = DupRow.find('#DateLoadedLbl').text();
var DupUserName = DupRow.find('#UserNameLbl').text();
var DupPlantLocation = DupRow.find('#PlantLocationLbl').text();
/// alert("DupLocationID: " + DuplicatesVisibleID + " DupLocation: " + DupLocation + " DupSection: " + DupSection + " DupTrailerNumber: " + DupTrailerNumber + " DupCarrierName: " + DupCarrierName);
$(".RowLocationDupDropDownList").hide();
// var $actualRow = $(row);
let text = DupSection + ' ' + DupLocation + ' ' + DuplicatesVisibleID;
$("select option").filter(function () {
//may want to use $.trim in here
return $(this).text() == text;
}).prop('selected', true);
$(".SelectedMoveToChecked").change(function () {
/// e.preventDefault();
//$('select.RowLocationDupDropDownList').each(function () {
if ($("select.SelectedMoveToChecked").closest('checked', true)) {
$(this).closest("tr").find('.RowLocationDupDropDownList').attr('disabled', true).show();
}
if ($('select.SelectedMoveToChecked').closest('checked', false)) {
$('.SelectedMoveToChecked').closest('checked', false).css('visibility', 'hidden');
}
$('select.RowLocationDupDropDownList').children("option:selected").text(DupSection + ' ' + DupLocation + ' ' + DuplicatesVisibleID);
/**********************************************************/
/********** Start Confirmation Dialogue Options ***********/
/**********************************************************/
if ($(this).children("option:selected").val() != '') {
function DuplicateMoveConfirm() {
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? \n" + " TrailerNumber: " + DupTrailerNumber + " CarrierName: " + DupCarrierName + " \n\n " + " From Duplicate Row: \n"
+ " Section: " + DupSection + " Location:" + DupLocation + " Row ID:" + DuplicatesVisibleID + " \n\n ";
if (confirm("Confirm Move Aready Existing To Current Row! " + ConfirmStr + "To Current Row: \n" + " Section: " + CurrentSection + " Location: " + CurrentLocation + " Row ID: " + CurrentLocationID + "?")) {
confirm_value.value = "Yes";
//Trigger/Handler from Drop-Down Box Change.
$("body").on("change", ".SelectedMoveToChecked", function () {
// $("body").on("change", "#TrailerNumber", function (e) {
// e.preventDefault();
/// var row = $(this).closest("tr");
var row = $("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible'); //Focus on the other row, not current row.
$("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) 9 Items where data comes from.
var ToRow = {};
// ToRow.LocationID = RowLocationIDNum;
ToRow.LocationID = CurrentLocationID;
//ToRow.LocationID = DuplicatesVisibleID;
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();
// setInterval('location.reload()', 777);
//Set the Clear Event to clear the initial rows.
/// var row = $(this).closest("tr");
var row = $("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible'); //Focus on the other row, not current row.
$("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 Duplicate Row After Moving the Data to the Current Row.
// clear.LocationID = DuplicatesVisibleID;
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/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
$.ajax({
type: "POST",
url: "/Home/ClearCustomer",
data: '{clear:' + JSON.stringify(clear) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
})
}
})
setInterval('location.reload()', 777);
})
}
else {
confirm_value.value = "Cancel";
setInterval('location.reload()', 777);
}
document.forms[0].appendChild(confirm_value);
}
DuplicateMoveConfirm();
}
});
}
});
//It finds when both TrailerNumber and CarrierName, but also finds when just TrailerNumber, even though CarrierName is not the same.
Related
I want to pass value through jQuery Json.The problem is that while passing the value then,it have some problem,thats why it is not calling c# code.
This is the html table:
$(function ()
{
debugger
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm7.aspx/BindCategoryDatatable",
data: "{}",
dataType: "json",
success: function (dt) {
debugger;
for (var i = 0; i < dt.d.length; i++) {
$("#tblid > tbody").append("<tr><td> <input type='checkbox' class='chk' id=" + dt.d[i].projectid + " /></td><td>" + dt.d[i].projectname + "</td><td>" + dt.d[i].Name + "</td><td>" + dt.d[i].technology + "</td><td>" + dt.d[i].projectliveurl + "</td><td><input type='image' src=" + dt.d[i].StatusImage + " onclick='actvstatus(" + dt.d[i].projectid + ", " + dt.d[i].status + ")' alt='Submit' width='18' height='18'> </td><td>" + dt.d[i].DisplayOrder + "</td><td> <i class='ui-tooltip fa fa-pencil' onclick='btnQueryString_Click(" + dt.d[i].projectid + ")' style='font-size:22px;margin-left: 32px;'></i><i class='ui-tooltip fa fa-trash-o' onclick='deleteRecord(" + dt.d[i].projectid + ")' style='font-size: 22px;margin-left: 32px;color:red'></i> </tr>");
}
$("#tblid").DataTable();
},
error: function (result) {
alert("Error");
}
});
});
This is my c# Code:
[WebMethod]
public static List<mProjects> BindCategoryDatatable(int catid)
{
clsProjectBL objcategory = new clsProjectBL();
List<mProjects> modelCategory = new List<mProjects>();
DataTable dtCategory = new DataTable();
//dtCategory = objcategory.GetAllCategoryDetails("admin");
dtCategory = objcategory.GetAllProjectDetails("admin", catid);
if (dtCategory.Rows.Count > 0)
{
modelCategory = (from DataRow dr in dtCategory.Rows
select new mProjects()
{
projectid = Convert.ToInt32(dr["projectid"]),
CategoryID = Convert.ToInt32(dr["CategoryID"]),
projectname = dr["projectname"].ToString(),
Name = dr["Name"].ToString(),
technology = dr["technology"].ToString(),
projectliveurl = dr["projectliveurl"].ToString(),
DisplayOrder = Convert.ToInt32(dr["DisplayOrder"]),
status = Convert.ToBoolean(dr["status"]),
StatusImage = dr["StatusImage"].ToString(),
//Deleted = Convert.ToBoolean(dr["Deleted"])
}).ToList();
}
return modelCategory;
}
The value is not pass through webmethod...
Your back-end required a parameter catid so you have to pass catid to AJAX call as #BenG and #palash answer with data attribute.
data: { catid: 1 }
Or you pass it to the url with format
url: "WebForm7.aspx/BindCategoryDatatable?catid=" + YOUR_ID.
Otherwise, it will not be worked because BindCategoryDatatable return an empty list.
I am creating a webpage in which I fetch top 8 rows from database on page load. I put load more button on my bottom of my web page. What I want is when I click on load more button it shows me next new 8 rows and skip previous records and if there is no new record found then show me nothing.
Below is my code which I was trying but it was repeating same duplicate records.
//Below event is fetching top 8 rows on page load
function viewAllEvents() {
$.ajax({
url: "Event.aspx/viewEvents",
data: null,
contentType: "Application/json; charset=utf-8",
responseType: "json",
method: "POST",
success: function (response) {
var x = response.d;
for (var i = 0; i < x.length; i++) {
$("#tabss > .event-container > .row").append(
"<div class='col-md-3'><div class='event'><div class='eventsimg'><img src= " + '../MediaUploader/' + x[i].EVE_IMG_URL + " alt=''></div><div class='event-content'><h3 class='title'>" + x[i].EVE_NAME + "</h3><p>" + x[i].EVE_DESCRIPTION + "</p><input type='button' id=" + i + " class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;' onClick='eveReq(" + i + ", " + x[i].ID + ", " + x[i].EVE_CAT_ID + ");' value='Send Request' /><input type='button' class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;margin-left: 2px;' value='Read More' /></div><div class='links clearfix'></div></div></div>"
);
}
},
error: function (xhr) {
alert(xhr.status);
},
Failure: function (response) {
alert(response);
}
});
}
//Below event is for when load more button is clicked
function addTabs() {
$.ajax({
url: "Event.aspx/addTab",
data: null,
contentType: "Application/json; charset=utf-8",
responseType: "json",
method: "POST",
success: function (response) {
var x = response.d;
for (var i = 0; i < x.length; i++) {
$("#tabss > .event-container > .row").append(
"<div class='col-md-3'><div class='event'><div class='eventsimg'><img src= " + '../MediaUploader/' + x[i].EVE_IMG_URL + " alt=''></div><div class='event-content'><h3 class='title'>" + x[i].EVE_NAME + "</h3><p>" + x[i].EVE_DESCRIPTION + "</p><input type='button' id=" + i + " class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;' onClick='eveReq(" + i + ", " + x[i].ID + ", " + x[i].EVE_CAT_ID + ");' value='Send Request' /><input type='button' class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;margin-left: 2px;' value='Read More' /></div><div class='links clearfix'></div></div></div>"
);
}
},
error: function (xhr) {
alert(xhr.status);
},
Failure: function (response) {
alert(response);
}
});
}
Below is my web methods:
[WebMethod]
public static List<EVENT> viewEvents()
{
var slist = new List<EVENT>();
var db = new BLUEPUMPKINEntities();
db.Configuration.LazyLoadingEnabled = false;
slist = db.EVENTS.OrderByDescending(eve => eve.ID).Take(8).ToList();
return slist;
}
[WebMethod]
public static List<EVENT> addTab()
{
var slist = new List<EVENT>();
var db = new BLUEPUMPKINEntities();
db.Configuration.LazyLoadingEnabled = false;
slist = db.EVENTS.OrderByDescending(eve => eve.ID).Skip(8).Distinct().ToList();
return slist;
}
Though I didn't use your code but I believe if you can go through this example below then you'll know what to do:
First declare a global variable which will count the record returned so far:
private int recordCount = 0;
Then in the click event do the following:
//My sample data
int[] data = { 1, 2, 3, 4, 5, 6, 7, 8 };
var results = data.Skip(recordCount).Take(2);
//Increment recordCount by the count of the results return above
recordCount+= results.Count();
if (results.Count() > 0)
{
//return results
}
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 .
I need to create a dropdownlist with the Region (Asia, South East Asia, North America,..etc) and the Country together in the same dropdownlist.
Upon selecting the options, then i will populate the City based on the Country selected.
It will look something like this, but in a dropdownlist instead of expanding it out.
With Singapore, Australia, Cambodia,etc as Region in my case, and the Cities shown, as Country.
Or more specifically, like the following , with Taiwan, Mainland China as Region, and the Cities as Country for my case.:
All my data are pulled from my database, with my RegionTable that looks like this
and my CountryTable like this :
I've got the code working fine for populating the cities based on Country selected, the problem now is that i do not know how to put the region into the same dropdown with the Country. The only problem is how do i add in the Region and making it not selectable because, users should be selecting the Country instead of the Region.
Im using the following code to get my CountryDropDownList
function loadPackage_CountryList() {
$('#Package_Country option').each(function (i, option) { $(option).remove(); });
$('#Package_Country').attr('disabled', true);
$("#Package_Country").append("<option value=''>Downloading...</option>");
$.ajax({
type: "POST", url: PackageWSURL + "/GetPackageCountryList", data: "",
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (response) {
var countries = response.d;
$('#Package_Country option').each(function (i, option) { $(option).remove(); });
$('#Package_Country').attr('disabled', false);
for (var i = 0; i < countries.length; i++) {
$("#Package_Country").append("<option value='" + countries[i].Value + "'>" + countries[i].Display + "</option>");
}
}
});
}
Anybody can help me on how to add Region into the Dropdownlist?
Thanks in advance.
--------------Edited----------------------
This is my WebMethod of getting the data from my database.
[WebMethod]
public List<jsonItem> GetPackageCountryList()
{
List<jsonItem> RecordList = new List<jsonItem>();
jsonItem jItemA = new jsonItem();
jItemA.Display = "All Countries";
jItemA.Value = "ALL";
jItemA.Group = "---";
RecordList.Add(jItemA);
String ConnStr = WebConfigurationManager.ConnectionStrings["TOUR_DB_ConStr"].ConnectionString;
SqlConnection connection = new SqlConnection(ConnStr);
connection.Open();
try
{
String SQL = "SELECT [CountryList].[CountryCode], [CountryList].[CountryName], [CountryList].[Regioncode] ";
SQL += "FROM [CountryTable] ";
SQL += "WHERE [CountryTable].[Activation] = 1 ";
SQL += "ORDER BY [CountryTable].[Regioncode], [CountryTable].[CountryName]";
SqlCommand command = new SqlCommand(SQL, connection);
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
jsonItem RecordItem = new jsonItem();
RecordItem.Display = dataReader["CountryName"].ToString() + " - " + dataReader["CountryCode"].ToString();
RecordItem.Value = dataReader["CountryCode"].ToString();
RecordItem.Group = getRegionName(dataReader["RegionCode"].ToString());
RecordList.Add(RecordItem);
}
dataReader.Close();
}
catch { }
finally
{
connection.Close();
}
return RecordList;
}
I've managed to add in the optgroup from the function below, but the problem now is that i think it will auto add in the <optgroup> at the end of the line even though i've add in the if else function.
function loadPackage_CountryList() {
$('#Package_Country option').each(function (i, option) { $(option).remove(); });
$('#Package_Country').attr('disabled', true);
$("#Package_Country").append("<option value=''>Downloading...</option>");
$.ajax({
type: "POST", url: PackageWSURL + "/GetPackageCountryList", data: "",
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (response) {
var countries = response.d;
var group = "";
$('#Package_Country option').each(function (i, option) { $(option).remove(); });
$('#Package_Country').attr('disabled', false);
for (var i = 0; i < countries.length; i++) {
group = countries[i].Group;
if (group != "---") {
$("#Package_Country").append("<optgroup label='" + countries[i].Group + "'><option value='" + countries[i].Value + "'>" + countries[i].Display + "</option>");
if (group != countries[i].Group)
{ $("#Package_Country").append("</optgroup>"); }
else { continue; }
}
else { $("#Package_Country").append("<option value='" + countries[i].Value + "'>" + countries[i].Display + "</option>"); }
}
}
});
}
so now it looks like this instead
notice how Asia got repeated.
I think you should use optgroup feature of select. If you can point the tech you use (WebForms, MVC) I can further help
Edit
I would change your for with this code
var selectCountries = $("select#Package_Country");
for (var i = 0; i < countries.length; i++) {
group = countries[i].Group;
var optgroupRegion = null;
if (group !== "---") {
optgroupRegion = selectCountries.find("optgroup[label='" + group + "']");
if (optgroupRegion.length === 0) {
optgroupRegion = $("<optgroup></optgroup>").attr("label", group).appendTo(selectCountries);
}
}
$("<option></option>").val(countries[i].Value).text(countries[i].Display).appendTo(optgroupRegion !== null ? optgroupRegion : selectCountries);
}
The updated code would reuse an already added optgroup.
Nothing happaned when i try do this in release mode but in debug mode all work fine - why???
When i adding button and outputing data by clicking this buton.My inner links in my list rows work fine also ( http://clip2net.com/s/2AG04 ).And only on $(document).ready(function () { event this doesn't want to work...
On client i have:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Index", "Product")',
cache: false,
type: 'GET',
dataType: 'json',
proccessData: false,
contentType: 'application/json; charset=utf-8'
});
On server i have this:
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
//Отправляем на клиент данные
_senderHub.SendMessage();
return null;
}
return View();
}
Also on server:(SignalR)
readonly ManagerDB _managerDB = new ManagerDB();
public void SendMessage()
{
IEnumerable<ProductModels> list = _managerDB.GetListOfProduct1();
var listToClient = new List<ProductModels>();
foreach (var prod in list)
{
listToClient.Add(new ProductModels
{
Id = prod.Id,
Name = prod.Name,
LockType = prod.LockType,
LockTime = prod.LockTime,
LockUser = prod.LockUser,
TimeStampF = prod.TimeStampF
});
}
var anonimProduct = listToClient;
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SenderHub>();
context.Clients.AddListRows(anonimProduct);
}
On client(SignalR) trying catch this data:
$(function () {
var senderHub = $.connection.senderHub;
senderHub.AddListRows = function (data) {
var dataFromServer = data;
var listOfData = "";
for (var i = 0; i < dataFromServer.length; i++) {
$("#ListOfProductsTableBody").html(null);
var userId = '';
if (dataFromServer[i].LockUser != null) {
userId = dataFromServer[i].LockUser;
}
listOfData += ("<tr><td>" + dataFromServer[i].Id + "</td><td>" + dataFromServer[i].Name + "</td><td>" + userId + "</td><td>" + dataFromServer[i].LockType + "</td>" + "<td id=\"ModifyBlock\"><a id=\"Detail\" href=\"#\" alt=" + dataFromServer[i].Id + " >Детально</a>|<a id=\"Delete\" href=\"#\" alt=" + dataFromServer[i].Id + " >Удалить</a>|<a id=\"Edit\" href=\"#\" class=\"" + dataFromServer[i].LockTime + "\" alt=" + dataFromServer[i].Id + " >Редактировать</a></td></td></tr>");
}
$("#ListOfProductsTableBody").append(listOfData);
};
$.connection.hub.start();
});
emphasized text
See David Fowler's response to my question. Looks like you have the same issue.
Server to client messages not going through with SignalR in ASP.NET MVC 4