Recover id in display list using combobox - c#

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 .

Related

MVC Razor, LINQ into J-Query?

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.

Ajax Response Doesn't work from server side (iis)

I try to save a file (image) on C# MVC and JS with the following function js
function Add() {
var data = new FormData();
var files = $("#txtUploadFile").get(0).files;
var cod = document.getElementById('cod').value;
var mat = document.getElementById('mat').value;
var status = document.getElementById('status').value;
var plant = document.getElementById('plant').value;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
data.append("mat", mat);
data.append("status", status);
data.append("plant", plant);
data.append("code", cod);
}
$.ajax({
type: 'POST',
url: '/Pred/Admin/AddPred',
contentType: false,
processData: false,
data: data,
success: function (response) {
if(response.msg == 1)
{
refreshTable(response.data);
}
alert('Predio agregado.');
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
}
});
}
}
}
and on the codebehind I used it
public ActionResult AddPred()
{
int isInsert=0;
string route = ConfigurationManager.AppSettings["MAPS_ROUTE"];
string[] status, plants, mats, codes;
int stat;
try
{
var requeststatus = Request.Params;
status = requeststatus.GetValues("status");
plants = requeststatus.GetValues("plant");
codes = requeststatus.GetValues("cod");
mats = requeststatus.GetValues("mat");
if (status[0] == "On")
stat= 1;
else
stat= 0;
string plant = plants[0];
string mat = mats[0];
string code = codes[0];
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
var fileName = fileContent.FileName;
var path = Path.Combine(Server.MapPath(route), fileName);
path = Server.MapPath(route) + fileName;
var sqlpath = "." + route + "/" + fileName;
fileContent.SaveAs(path);
isInsert = ma.InsertPred(code, mat, stat, plant, sqlpath);
}
}
merge.preds = ma.GetPreds();
return Json(new { success = true, data = merge.preds, msg = isInsert }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("add failed");
}
}
But the server response ever is
POST myserver/Preds/Admin/AddPred 500 (Internal Server Error)
and I used console.log but I can't to get the error information, When used this code on local side, it's runs Okey, save the image and return model for refresh the front, but when put the aplication on the server, only return error, others funtions works (modal show, return model with json) but doesn't work save a image, I set permissions (write, load, modify) on the server folder,
someone give a idea for solves this problem, I don't know whats wrong
Try like this :
function getCities(id) {
$.ajax({
type: "POST",
url: "#Url.Action("Index", "Default")",
data: '{id: id }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert(response.responseData);
window.location = '/Default/YourView';//
},
error: function (response) {
alert("error!"); //
}
});
}
//In your controller
public JsonResult Index(string id)
{
merge.country= mp.Country();
merge.city= mp.City(id);
return Json("you can return an object or a string, what you want");
}

Phonegap Filetransfer Upload Issue with WCF OData

I am trying to upload file using phonegap "FileTransfer". I am using .NET WCF OData for uploading the image.
The "upload" function not calling my API, and returns the below error message:
{"code":null,"source":null,"http_stats":null,"body":null}
my described code is as below:
navigator.camera.getPicture(function(imageURI){
var url = encodeURI("http://api.xyz.com/DataService/DataService.svc/UploadImage");
var params = new Object();
params.id= parseInt(1);
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.params = params;
options.chunkedMode = true;
var ft = new FileTransfer();
ft.upload(imageURI, url, function (data) { alert(JSON.stringify(data)) }, function (data) { alert(JSON.stringify(data)) }, options);
}
and my WCF OData code is as below:
[WebInvoke]
public void UploadImage(int id)
{
// **what to write here???**
}
I also tried with following code but window.resolveLocalFileSystemURI function throws an Error calling method on NPObject error
navigator.camera.getPicture(function (imageURI) {
var _this = this;
var encodedURL = encodeURI("http://api.xyz.com/DataService/DataService.svc/UploadImage");
try {
this.op = new FileUploadOptions();
this.op.fileKey = "file";
this.op.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
this.op.mimeType = "image/jpeg";
this.op.chunkedMode = false;
this.op.headers = { Connection: "close" };
this.ft = new FileTransfer();
if (window.device != undefined && device.platform == "Android") {
window.resolveLocalFileSystemURI(imageURI, function (fileEntry) {
fileEntry.file(function (fileObj) {
var fileFullPath = fileObj.fullPath;
_this.op.fileName = fileFullPath.substr(fileFullPath.lastIndexOf('/') + 1);
_this.ft.upload(fileFullPath, encodedURL, function (data) { alert("Success: " + JSON.stringify(data)); }, function (data) { alert("Failour: " + JSON.stringify(data)); }, _this.op, true);
});
});
} else {
this.ft.upload(imageURI, encodedURL, function (data) { alert("Success: " + JSON.stringify(data)); }, function (data) { alert("Failour: " + JSON.stringify(data)); }, this.op, true);
}
} catch (_error) {
alert(_error);
}
},
function (message) { },
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
});
}

Country/Region and City List in a dropdownlist

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.

When i try send data from server to client nothing happened

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

Categories

Resources