mvc 5 and jquery post not working second time - c#

the code on the belows add/remove/list products to cart, it works first time correctly, when i add second product its not refresh cart, when i refresh cart, i see second product. Anyone help me what i forget?
Note: Controller method returns JsonResult
jQuery(document).ready(function () {
jQuery('#vmCartModule').hover(
function () {
jQuery('#cart_list').stop(true, true).slideDown(400)
},
function () {
jQuery('#cart_list').stop(true, true).delay(500).slideUp(100)
}
)
new Request.HTML({
'url': 'Sepetim/Sepet',
'method': 'get',
'data': '',
'onSuccess': function (tree, elms, html, js) {
//jQuery(".vmCartModule").productUpdate();
mod = jQuery(".vmCartModule");
jQuery.getJSON(vmSiteurl + "Sepetim/Sepet",
function (datas) {
if (datas == null) {
mod.find(".text-cart").html("Sepetiniz Boş"); // Sepet boş
mod.find(".vm_cart_products").html("");
mod.find(".total").html("");
mod.find(".show_cart").html("");
}
else if (datas.ProductCount > 0) { // Ürün sayısı
//mod.find(".vm_cart_products").html("");
mod.find(".cart_list").html("");
mod.find(".crt-text").html(datas.ProductCount + " ürün mevcut");
datas.CartList.reverse();
jQuery.each(datas.CartList, function (key, val) {
if (key < 4) {
jQuery("#hiddencontainer .container").clone().appendTo(".vmCartModule .vm_cart_products");
jQuery.each(val, function (key, val) {
if (jQuery("#hiddencontainer .container ." + key)) {
mod.find(".vm_cart_products ." + key + ":last").html(mod.find(".vm_cart_products ." + key + ":last").html() + val);
}
});
}
});
mod.find(".total").html("Toplam Tutar: " + datas.TotalAmount + "TL"); //Toplam Tutar
mod.find(".show_cart").html(datas.ShowCart);
} else {
mod.find(".text-cart").html("Sepetiniz Boş"); // Sepet boş
mod.find(".vm_cart_products").html("");
mod.find(".total").html("");
mod.find(".show_cart").html("");
}
}
);
}
}).send();
});
function add_product_cart(elm) {
var cart_id = jQuery(elm).children("span.product_cart_id").text();
new Request.HTML({
'url': 'Sepetim/SepeteUrunEkle',
'method': 'post',
'data': 'productID=' + cart_id + '&count=' + 1,
'onSuccess': function (tree, elms, html, js) {
mod = jQuery(".vmCartModule");
jQuery.getJSON(vmSiteurl + "Sepetim/Sepet?callback=",
function (datas) {
if (datas.ProductCount > 0) { // Ürün sayısı
mod.find(".vm_cart_products").html("");
mod.find(".cart_list").html("");
mod.find(".crt-text").html(datas.ProductCount + " ürün mevcut");
datas.CartList.reverse();
jQuery.each(datas.CartList, function (key, val) {
if (key < 4) {
jQuery("#hiddencontainer .container").clone().appendTo(".vmCartModule .vm_cart_products");
jQuery.each(val, function (key, val) {
if (jQuery("#hiddencontainer .container ." + key)) mod.find(".vm_cart_products ." + key + ":last").html(val);
});
}
});
mod.find(".total").html("Toplam Tutar: " + datas.TotalAmount + "TL"); //Toplam Tutar
mod.find(".show_cart").html(datas.ShowCart);
} else {
mod.find(".text-cart").html("Sepetiniz Boş"); // Sepet boş
mod.find(".vm_cart_products").html("");
mod.find(".total").html("");
mod.find(".show_cart").html("");
}
}
);
}
}).send();
}
function remove_product_cart(elm) {
var cart_id = jQuery(elm).children("span.ProductID").text();
new Request.HTML({
'url': 'Sepetim/SepettenUrunSil',
'method': 'post',
'cache': false,
'datatype': JSON,
'data': 'productID=' + cart_id,
'onSuccess': function (tree, elms, html, js) {
mod = jQuery(".vmCartModule");
jQuery.getJSON(vmSiteurl + "Sepetim/Sepet?callback=",
function (datas) {
if (datas.ProductCount > 0) { // Ürün sayısı
mod.find(".vm_cart_products").html("");
mod.find(".cart_list").html("");
mod.find(".crt-text").html(datas.ProductCount + " ürün mevcut");
datas.CartList.reverse();
jQuery.each(datas.CartList, function (key, val) {
if (key < 4) {
jQuery("#hiddencontainer .container").clone().appendTo(".vmCartModule .vm_cart_products");
jQuery.each(val, function (key, val) {
if (jQuery("#hiddencontainer .container ." + key)) mod.find(".vm_cart_products ." + key + ":last").html(val);
});
}
});
mod.find(".total").html("Toplam Tutar: " + datas.TotalAmount + "TL"); //Toplam Tutar
mod.find(".show_cart").html(datas.ShowCart);
} else {
mod.find(".text-cart").html("Sepetiniz Boş"); // Sepet boş
mod.find(".vm_cart_products").html("");
mod.find(".total").html("");
mod.find(".show_cart").html("");
}
}
);
}
}).send();
}
Thanks

Related

Jquery returns value "undefined" .net core

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();
},

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.

Why my code is repeated in async upload file web api

In upload async file :
for example if i uploading 3 file Debug.WriteLine(info.FullName); and _db.Files.Add(New FileDto{FileName=info.Name}); repeated 50 time.means 50 record insert in database.
Why and how to avoid it?
what is my problem?
public Task<IEnumerable<FileDesc>> Post()
{
string folderName = "uploads";
string PATH = HttpContext.Current.Server.MapPath("~/" + folderName);
string rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new CustomMultipartFormDataStreamProvider(PATH);
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDesc>>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
Debug.WriteLine(info.FullName);//************Repeated******
_db.Files.Add(New FileDto{FileName=info.Name});//************Repeated******
return new FileDesc(info.Name, rootUrl + "/" + folderName + "/" + info.Name, info.Length / 1024);
});
return fileInfo;
});
return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
[Update]
CustomMultipartFormDataStreamProvider :
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path)
: base(path)
{
}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName";
return name.Replace("\"", string.Empty);
}
}
[Update]
$('#fileupload').fileupload({
dataType: "json",
url: "/media/upload",
limitConcurrentUploads: 1,
sequentialUploads: true,
progressInterval: 100,
maxChunkSize: 10000,
add: function (e, data) {
$('#filelistholder').removeClass('hide');
data.context = $('<div />').text(data.files[0].name).appendTo('#filelistholder');
$('<div class="progress progress-striped active"><div style="width: 0%;" class="progress-bar progress-bar-warning"></div></div>').appendTo(data.context);
$('#btnUploadAll').click(function () {
data.submit();
});
},
done: function (e, data) {
data.context.text(data.files[0].name + '... Completed');
$('<div class="progress progress-striped active"><div style="width: 100%;" class="progress-bar progress-bar-success"></div></div>').appendTo(data.context);
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#overallbar').css('width', progress + '%');
},
progress: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
data.context.find('.progress-bar').css('width', progress + '%');
}
});
Your Debug.WriteLine is in the projection function of streamProvider.FileData.Select, so it is executed as many times as there are items in streamProvider.FileData.

Getting Null for .val()

I have inputs and selects. For some reason, some of them are giving me a null. Here is the code:
<script type="text/javascript">
$(function () {
$('#add').on('click', function () {
$('table').append('<tr>' +
'<td><button class=\'save\'>Save</button></td>' +
'<td><input name=\'name\' id=\'companyName\' /></td>' +
'<td><input name=\'currency\' id=\'currency\' /></td>' +
'<td><input name=\'ISOCode\' id=\'ISOCode\' /></td>' +
'<td><input name=\'CalcDeadLine\' id=\'CalcDeadLine\' /></td>' +
'<td><select name=\'mealAlgorithm\' id=\'mealAlgorithm\'><option value="True">Yes</option><option value="False">No</option></select></td>' +
'<td><input name=\'breakfast\' id=\'breakfast\' /></td>' +
'<td><input name=\'halfBoard\' id=\'halfBoard\' /></td>' +
'<td><input name=\'fullBoard\' id=\'fullBoard\' /></td>' +
'<td><input name=\'adminID\' id=\'adminID\' /></td>' +
'<td><input name=\'language\' id=\'language\' /></td>' +
'<td><input name=\'approvalcid\' id=\'cid\' /></td>' +
'<td><select name=\'useSMS\' id=\'useSMS\'><option value="True">Yes</option><option value="False">No</option></select></td>' +
'<td><select name=\'active\' id=\'active\'><option value="True">Yes</option><option value="False">No</option></select></td>');
$('#add').hide();
})
});
$(".save").live("click", function () {
var name = $("#companyName").val();
var currency = $("#currency").val();
var isoCode = $("#ISOCode").val();
var calcDeadLine = $("#CalcDeadLine").val();
var mealAlgorithm = $("#mealAlgorithm").val();
var noMeal = 111;
var breakfast = $("#breakfast").val();
var halfBoard = $("#halfBoard").val();
var fullBoard = $("#fullBoard").val();
var adminID = $("#adminID").val();
var language = $("#language").val();
var cid = $("#cid").val();
var useSms = $("#useSMS").val();
var active = $("#active").val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("SaveCompany", "Admin")',
data: {
"CompanyName": name, "Currency": currency, "ISOCompanyCode": isoCode, "CalcDeadline": calcDeadLine,
"UseMealAlgorithm": mealAlgorithm, "NoMeal": noMeal, "Breakfast": breakfast, "HalfBoard": halfBoard,
"FullBoard": fullBoard, "AdminUserID": adminID, "ApprovalCulture": language, "ApprovalLcid": cid,
"UseSMS": useSms, "Active": active},
dataType: "json",
beforeSend: function () {
},
success: function (data) {
if (data.result == true) {
$("#GridCompany").html("Record has been saved!");
}
else {
alert("There is some error.");
}
}
})
})
In url of post everything is ok, it has true/false and every parameter with every value fulfilled.
In my controller I have
[HttpGet]
public JsonResult SaveCompany(string name, string currency, string isoCode, int calcDeadline, bool? mealAlgorithm,
int noMeal, int breakfast, int halfBoard, int fullBoard, string adminUserId, string approvalCulture,
int? approvalCid, bool? useSms, bool? active)
{
bool result = false;
try
{
result = _companyRepository.SaveCompany(name, currency, isoCode, calcDeadline, mealAlgorithm, noMeal,
breakfast, halfBoard, fullBoard, adminUserId, approvalCulture, approvalCid, useSms, active);
}
catch(Exception ex)
{
}
return Json(new { result }, JsonRequestBehavior.AllowGet);
}
Nulls are isoCode, mealAlgorithm, approvalCid.
The problem is the wrong names of the fields.
In the AJAX you pass ISOCompanyCode but in the Action you're waiting for isoCode
The same is for the other two fields (you have different names). Use the same names and it'll fix your problem.

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