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
Related
I want to populate second dropdown from first one.
It all works but city names and values just returns "undefined". *Number of cities returns correct but the name and value are always "undefined". *
Controller:
[HttpPost]
public ActionResult getCityJson(string stateId)
{
int _stateid = Convert.ToInt32(stateId);
List<Cities> objcity = new List<Cities>();
objcity = _db.Cities.Where(m => m.stateID == _stateid).ToList();
SelectList obgcity = new SelectList(objcity, "CityID", "CityName", 0);
return Json(obgcity);
}
View Page:
$("#istateid").change(function () {
var id = $("#istateid").val();
$.ajax({
url: '#Url.Action("getCityJson", "Home")',
data: { stateId: id },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#icityid").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
I also tried Public JsonResult and return JsonResult and Public Selectlist and return SelectList but none of them worked.
And I also tried this:
$("#istateid").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("getCityJson", "Home")',
data: { stateId: $("#istateid > option:selected").attr("value") },
success: function (data) {
var items = [];
items.push("<option>--Choose Your City--</option>");
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#icityid").html(items.join(' '));
}
}) });
I recieve this in browser:
(TypeError: data[x] is undefined.)
$("#istateid").change(function () {
var id = $("#istateid").val();
$.ajax({
url: '/Home/getCityJson',
data: { stateId: id },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++)
{ markup += "<option value=" + data[x].CityID + ">" + data[x].CityName + "</option>"; }
$("#icityid").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
<option value="0">Select City</option>
<option value="undefined">undefined</option>
<option value="undefined">undefined</option>
<option value="undefined">undefined</option>
Solved:
items.push("<option value=" + this.value + ">" + this.text + "</option>");
Value and text camel cased.
Special thanks to #agua from mars
Other codes I tried:
$("#istateid").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("getCityJson", "Admin")',
data: { stateId: $("#istateid > option:selected").attr("value") },
success: function (data) {
var items = [];
items.push("<option>--Choose Your Area--</option>");
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#icityid").html(items.join(' '));
}
})
});
Controller:
[HttpPost]
public JsonResult getCityJson(string stateId, string selectCityId = null)
{
return Json(getCity(stateId, selectCityId));
}
public SelectList getCity(string stateId, string selectCityId = null)
{
IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
if (!string.IsNullOrEmpty(stateId))
{
int _stateId = Convert.ToInt32(stateId);
cityList = (from m in db.Cities where m.StateID == _stateId select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.CityName, Value = m.CityID.ToString() });
}
return new SelectList(cityList, "Value", "Text", selectCityId);
}
try this:
success: function (data) {
var response=JSON.parse(data);
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < response.length; x++)
{ markup += "<option value=" + response[x].CityID + ">" + response[x].CityName + "</option>"; }
$("#icityid").html(markup).show();
},
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 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.
I have the following code where the function codeaddress geocodes the text feild value and returns geocoded value , geocoded value is stored in variable example ,how will i return the variable v2 to the function call and post to asmx webservice.
<script type="text/javascript">
$(document).ready(function() {
$('#SubmitForm').submit(function() {
var geocoder;
var map;
function codeAddress(state) {
var address = document.getElementById("state").value;
geocoder.geocode( { 'address': state}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var v2=results[0].geometry.location;
alert(example);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
return v2;
});
var businessname = ($("#businessname").val());
var keyword = ($("#keyword").val());
var description = ($("#textarea").val());
var zipcode = ($("#zipcode").val());
var streetno = ($("#streetno").val());
var streetname = ($("#streetname").val());
var state = $('#state :selected').text();
var telephone = ($("#telephone").val());
var email = ($("#email").val());
var username = ($("#username").val());
var password = ($("#pass").val());
var repassword = ($("#pass1").val());
//data: "{'businessname':" + businessname + "'keyword':" + keyword + "}",
alert(state);
var v2=codeAddress(state);
alert(example);
var jsonobject = "{\"businessname\":\"" + businessname + "\",\"keyword\":\"" + keyword + "\",\"description\":\"" + description + "\",\"zipcode\":\"" + zipcode + "\",\"streetno\":\"" + streetno + "\",\"streetname\":\"" + streetname + "\",\"state\":\"" + state + "\",\"telephone\":\"" + telephone + "\",\"email\":\"" + email + "\",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"repassword\":\"" + repassword + "\"}";
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
});
function ajaxCallFailed(error) {
alert("error");
}
function ajaxCallSucceed(response) {
if (response.d == true) {
alert(" sucessfully saved to database");
}
else {
alert("not saved to database");
}
}
});
</script>
You call the codeAddress method with a callback. Inside codeAddress when you get value of v2, call the callback function passing it v2.
codeAddress(state,
function(v2) {
var jsonobject = "{\"businessname\":\"" + businessname/*.. use v2 in buiding jsonobject..*/;
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
}
);
function codeAddress(state, callback) {
var address = document.getElementById("state").value;
geocoder.geocode(...);
// ...
var v2=results[0].geometry.location;
callback(v2);
}