I'm developing a shopping cart function.
I need product data from the server that used to render the shopping cart page.
Every time the Add-to-cart button is hit, I stringify this array ( using JSON.stringify() ):
var CART = [{productId: 102, quantity: 3} , {productId: 211, quantity: 6}];
I want to get this data using Request.Cookie["shoppingCart"] in my ASP.NET application,
but when I debug It is always null
This is what the browser return when I call document.cookie
"shoppingCart=[{\"productId\":101617121,\"quantity\":2}]"
But when I try to change the value of the cookie to something like: shoppingCart=testresult ,
the Request.Cookie["shoppingCart"] then has value.
Thank you in advance for helping me!
I solved it.
First, I tried to remove some special chars which are: " and , .
And Request.Cookie then had values. So it seems like ASP.NET just doesn't except these characters in cookie value. ( Tell me if I'm wrong please )
My solution was instead of convert JSON string, I used this formular for each product in the shopping cart : var item = `{productId}:{quantity}`; .
For example:
var sampleCookie = "11231:16:15121:8";
Split the string with : char then use a simple code to get the data.
My code for this:
string cookie = Request.Cookies["shoppingCart"];
var cartItems = new List<CartItem>();
if (cookie != null && cookie.Length > 0)
{
string[] values;
values = cookie.Split(':');
int i = 0;
while (i < values.Length)
{
cartItems.Add(new CartItem()
{
ProductId = values[i],
Quantity = Convert.ToInt32(values[i+1])
});
i += 2;
}
}
Related
I have a nopcommerce website. I find a problem. Please see below code
// My account / Order details page
[HttpsRequirement(SslRequirement.Yes)]
public virtual IActionResult Details(int orderId)
{
var order = _orderService.GetOrderById(orderId);
if (order == null || order.Deleted || _workContext.CurrentCustomer.Id != order.CustomerId)
return Challenge();
var orderTotal = order.OrderTotal;
order = _orderService.GetOrderById(orderId);
var orderTotal2 = order.OrderTotal;
var model = _orderModelFactory.PrepareOrderDetailsModel(order);
return View(model);
}
When I put a breakpoint on
var orderTotal = order.OrderTotal;
I get the value (100) of orderTotal from table Order. Then I changed the value of orderTotal from 100 to 200 in the database, and continue to execute the code.
order = _orderService.GetOrderById(orderId);
var orderTotal2 = order.OrderTotal;
This code should get the new value (200) of orderTotal from the table Order, however, it still returns a value of 100 for orderTotal2.
I want to get the refreshed data in function in the controller. Could you help me solve this problem?
Because the GetOrderById Method retrieves the cached order in the memory using 'ToCachedGetById', you can use GetOrderByGuid method instead to get the order directly from DB and skip the caching order
I want to apply where condition on Umbraco Collection.
Code:
var workList = CurrentPage.work.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
var workCollection = Umbraco.Content(workList);
#foreach (var item in workCollection.Where("productImage!=\"\"").Skip((i - 1) * iterationCount).Take(iterationCount))
But I always get data without filter.
ProductImage is media picker
If you want to stick to dynamic object, you should try:
var workList = CurrentPage.work.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
var workCollection = Umbraco.Content(workList);
#foreach (var item in workCollection.Where("productImage != null && productImage != string.Empty").Skip((i - 1) * iterationCount).Take(iterationCount)) { ... }
Personally, I prefer to deal with strongly typed objects, so another solution may be:
var workList = CurrentPage.work.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
var workCollection = Umbraco.TypedContent(workList);
#foreach (IPublishedContent item in workCollection.Where(x => x.HasValue("productImage")).Skip((i - 1) * iterationCount).Take(iterationCount)) { ... }
For more informations check: https://our.umbraco.org/documentation/reference/templating/mvc/querying.
You can also check a package called Umbraco Core Property Value Converters: https://our.umbraco.org/projects/developer-tools/umbraco-core-property-value-converters/ which is automatically converting some data type values into easily accessed objects / lists etc. E.g. media picker value is returned as IPublishedContent model and you can access it's properties directly from the returned value.
So I guess what you want to do is get items from workcollection that have a filled projectImage property?
I personally like to do this with a lambda expression, in your case it would be something like this
workCollection.Where(x => x.HasValue("productImage"))
instead of
workCollection.Where("productImage!=\"\"")
I'm using: ASP.NET MVC, MySql, Dapper.NET micro-orm
I made a stored procedure with 3 SELECTs, two of which returns lists and the third one returns an integer.
Here is my code:
using (var conn = new MySqlConnection(GetConnectionString()))
{
var readDb = conn.QueryMultiple(storedProcedure, parameters, commandType: CommandType.StoredProcedure);
var result = new someView
{
TopicsList = readDb.Read<ITopic>().ToList(),
TopTopicsList = readDb.Read<IMessage>().ToList(),
TopicsCount = readDb.Read<int>().Single()
};
return result;
}
In ITopic I have TopicId, in IMessage I have MessageId.
And here's the error:
When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id Parameter name: splitOn
I tried adding splitOn on both QueryMultiple and Read, and nigher accepted it.
Though I dont understand why I need splitOn? can't dapper see that I have three separate SELECTs? When using conn.Read(storedProcedure,parameters) on each of the selects separately (instead of MultipleQuery on all of the together) dapper has no problem mapping it to a given object.
What am I doing wrong?
1) Problem solved when I used the real models names instead of their interfaces names:
TopicView instead of ITopic, TopTopicsView instead of IMessage;
2) Once that was fixed and there was no longer "no splitOn" error, started another problem with the < int > casting in line:
TopicsCount = readDb.Read<int>().Single()
probably mysql doesnt return numbers back as ints?
I tried using decimal, object, dynamic, etc.. with no luck. Eventually fixed it by creating another Model with int property inside that has the same name as the database int parameter and now it works.
3) Here's the final working code:
using (var conn = new MySqlConnection(GetConnectionString()))
{
var parameters = context.MapEntity(query);
var multi = conn.QueryMultiple(storedProcedure, parameters, commandType: System.Data.CommandType.StoredProcedure);
var TopicsList = multi.Read<TopicView>().ToList();
var TopTopicsList = multi.Read<TopTopicsView>().ToList();
var result = multi.Read<HomeView>().Single();
result.TopicsList = TopicsList;
result.TopTopicsList = TopTopicsList;
return result;
}
Hi i'm looking for some help in how to append rows to an existing LINQ object. In the controller method below I have two result sets, i'm looping the Sites and want to add a record to the 'results' object for each record in the Sites object.
I've tried concat etc but not getting anywhere, just need s small example to assist, many thanks in advance, J
public IQueryable<UsersToSite> FindAllUsersToSites(int userId,SystemType obj)
{
var results = (from usersToSite in this._db.UsersToSites
where usersToSite.UserId == userId &&
usersToSite.SystemTypeId == obj
orderby usersToSite.Site.SiteDescription
select usersToSite);
// Now for each remaining Site append a record thats not physically in the database. From the view the user will be able to click these records to ADD new
// I'll then build in a search
var sites = (from site in this._db.Sites
where !(from o in _db.UsersToSites where (o.UserId == userId && o.SystemTypeId == obj) select o.SiteId).Contains(site.SiteId)
orderby site.SiteDescription
select site);
foreach (var site in sites)
{
// HERE I want to create the new ROW in results object
//results = new[results] { new { UsersToSiteId = null, AccessTypeId = null } }.Concat(sites);
//SiteId=site.SiteId,
//UsersToSiteId = 0,
//AccessTypeId = 0,
//UserId = userId
}
return results;
}
I don't think you can, if you want to have keep queryable.
However, if you materialize the results with ToList(), then you can:
var sites = (from site in this._db.Sites
where !(from o in _db.UsersToSites where (o.UserId == userId && o.SystemTypeId == obj) select o.SiteId).Contains(site.SiteId)
orderby site.SiteDescription
select site)
.ToList();
sites.Add(new Site { UsersToSiteId = null, etc });
If it was LINQ to Objects, you could do Concat.
The problem here that it can't do ConcatLINQ query that will have one part from SQL and another from objects. You need to materialize results first and then concat to object.
All I want to do is
Get the name-value pairs that were supplied to Request.QueryString
Populate a javascript object (aka hash) with keys from the names and values from the values
Halt the page if one of the expected hash values is the empty string
The Request.QueryString object is reminding me why I hated classic asp even before it was an abandoned technology. :/
The Request.QueryString collection has an awkward interface, particularly when it comes to iterating or cases where there are multiple params with the same name. I suggest grabbing the whole querystring using Request.QueryString.Item() or Request.ServerVariables('QUERY_STRING') and parse it using unescape/decodeURIComponent. It's a bit of effort, but gives you more control and consistency.
A simple example that lowercases keys:
var params = parseQueryString(Request.QueryString.Item());
function parseQueryString(qs) {
var parsed = {}, pairs = qs.split('&');
for (var i = 0; i < pairs.length; i ++) {
var pair = pairs[i], pos = pair.indexOf('=');
if (pos < 0) pos = pair.length;
parsed[unescape(pair.slice(0, pos)).toLowerCase()] = unescape(pair.slice(pos + 1));
}
return parsed;
}
Querystring contents are treated as string by default i believe..
But if you have to, you can always do String( request.querystring("foo") );
Are the keys known before-hand ? or you want to iterate through the pairs and retrieve both key and value ?