Hi I want to save my last visited product detail page id in one cookie. For ex.first, ı am at random tire page and first cookie value 44 then visiting other pages url id 65 one by one. what should ı do? Can ı save them in List for cookie value because it's what ı need? thanks for helps.
public ActionResult DetailShow(int id)
{
string cokvalue = ControllerContext.RouteData.Values["id"].ToString();
List<string> view = new List<string>();
foreach (var item in cokvalue)
{
view.Add(cokvalue);
}
**This one for What ı want to add last visited pages
HttpCookie cok = new HttpCookie("last viewed");
cok.Values["last visited"] = string.Join(",", view.ToArray());
cok.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cok);
HttpCookie mycookie = new HttpCookie("Product");
mycookie.Values["asd"] = cokvalue;
mycookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(mycookie);
var product = gelistirmeEntities.Product.Where(p => p.Product_ID == id).FirstOrDefault();
return View(product);
}
THE ANSWER
public ActionResult DetailShow(int id)
{
string cokvalue = ControllerContext.RouteData.Values["id"].ToString();
HttpCookie cok = Request.Cookies["last viewed"];
List<string> cookielist = new List<string>();
cookielist.Add(cokvalue);
if (cok == null)
{
var serialize = JsonConvert.SerializeObject(cookielist);
cok = new HttpCookie("last viewed");
cok.Values["last visited"] = serialize;
}
else
{
cookielist.InsertRange(0,JsonConvert.DeserializeObject<List<string>>(cok.Values["last visited"]));
var serialize = JsonConvert.SerializeObject(cookielist);
cok.Values["last visited"] = serialize;
}
cok.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cok);
HttpCookie mycookie = new HttpCookie("Product");
mycookie.Values["asd"] = cokvalue;
mycookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(mycookie);
var product = gelistirmeEntities.Product.Where(p => p.Product_ID == id).FirstOrDefault();
return View(product);
}
Related
I have a table named Payment which has a column named IndexOrder and all I need when I add a new payment, the AddEdit function will check first if there is any value in IndexOrder Column for this specific Id then increment Indexorder with 1 and so on for every new PaymentId. my AddEdit function code is like:
[HttpPost]
public ActionResult AddEdit(PaymentModel model )
{
if (ModelState.IsValid)
{
var userId = User.Identity.GetUserId();
Payment obj = context.Payment
.Where(p => p.Id == model.Id).FirstOrDefault();
if (obj == null)
{
obj = new Payment();
if (model.File != null)
{
Guid nme = Guid.NewGuid();
string filename = nme + Path.GetExtension(model.File.FileName);
string filepath = Path.Combine(Server.MapPath("/FilesUpload/") + filename);
model.File.SaveAs(filepath);
obj.Path = filename;
}
Mapper.FillObjectFromModel(obj, model);
obj.CreatedBy = userId;
obj.ModifiedBy = userId;
obj.CreatedAt = DateTime.Now;
obj.ModifiedAt = DateTime.Now;
context.Payment.Add(obj);
context.SaveChanges();
So did i get that right? For every new payment that relates to a specific id (assuming a product or something) you want aincremented IndexOrder?
I would not use an IndexOrder column for that but instead just order by timestamp. Assuming you need that for kind of transactionhistory just read them payments like
context.Payments.Where(x => x.ProductId == myProductId).OrderBy(x => x.timestamp);
But to answer your question this should be quite simple, e.g:
var nextIndex = context.Payments.Where(x => x.ProductId == myProductId).Count +1;
How can I pass the input type text value to TempData
<input type='text' name='APP_COMMENT' />
#{TempData["APP"] = //This's where I want the input value;}
EDIT:
This's the action that I need to send from the View to Controller (Not Controller to view)
public ActionResult Approved()
{
Entities1 db = new Entities1();
string y=(TempData["APP"]).ToString(); //TempData is send from the View to Controller
decimal sl = (decimal)TempData["rt"];
var sp = db.TB_RST_SVCHDR.Where(x => x.REQ_NO == sl);
foreach (var p in sp)
{
if (p.STATUS == "N")
{
p.STATUS = "A1";
p.APP1_COMMENT = y; //Here's where the TempData is saved
p.APP1_DATEACTION = DateTime.Now;
p.APPROVER1 = "";
var s = p.APPROVER2;
//var ss = p.APPROVER2;
var s2 = p.REQUESTOR_EMPNAME;
TempData["email-act2"] = s2;
//SendEmail(s, ss);
SendEmail(s);
db.SaveChanges();
return View("~/Views/Home/Index.cshtml");
}
}
//return View();
return View("~/Views/Home/Index.cshtml");
}
However your question seems to look more of a Post action. In which case you should consider reading up on how to post data using a form. Use this.
#using (Html.BeginForm("Approved", "Controllername", FormMethod.Post))
{
<input type="text" name="data">
<input type="submit">
}
And set up the controller action like so:
[HttpPost]
public ActionResult Approved(string data)
{
Entities1 db = new Entities1();
string y= data;
decimal sl = (decimal)TempData["rt"];
var sp = db.TB_RST_SVCHDR.Where(x => x.REQ_NO == sl);
foreach (var p in sp)
{
if (p.STATUS == "N")
{
p.STATUS = "A1";
p.APP1_COMMENT = y; //Here's where the TempData is saved
p.APP1_DATEACTION = DateTime.Now;
p.APPROVER1 = "";
var s = p.APPROVER2;
//var ss = p.APPROVER2;
var s2 = p.REQUESTOR_EMPNAME;
TempData["email-act2"] = s2;
//SendEmail(s, ss);
SendEmail(s);
db.SaveChanges();
return View("~/Views/Home/Index.cshtml");
}
}
//return View();
return View("~/Views/Home/Index.cshtml");
}
Unless, you want something dynamic that updates TempData["APP"] when the input changes, what you can do is to assign the value when that form is posted. So, you do something of this nature.
public async Task<IActionResult> OnPostAsync(Model model)
{
model.YourField = TempData["APP"]
}
I am creating an internal site for my company, my landing page consists of tiles that are a mix of required and optional tiles. The list of tiles and their respective order are save in a cookie as a JSON string. I build the cookie just fine, i can update it whenever the order changes without a problem. I issue is when i have them click on the remove button on the optional tile. It will not remove it from the cookie.
Here is the code in the partial for the ajax request:
#Ajax.ActionLink(" ", "RemoveTile", "Home", new { id = "_EventsTile" }, new AjaxOptions { OnSuccess= "$(this).closest('.tilePartial').remove(); location.reload();" }, new { #class = "fas fa-clickable fa-window-close removeTile", #style = "color:red; font-size:1.5em; padding-top:1%" })
Here is the code of the action in the controller:
private void UpdateCookie(object obj, string cookieName, int expiredays = 30)
{
HttpCookie cookie = new HttpCookie(cookieName);
cookie.Value = JsonConvert.SerializeObject(obj);
cookie.Expires = DateTime.Now.AddDays(expiredays);
Response.SetCookie(cookie);
Response.Cookies.Add(cookie);
}
public void RemoveTile(string id)
{
List<TileInfo> newCookie = new List<TileInfo>();
var cookieInfo = JsonConvert.DeserializeObject<List<TileInfo>>(Request.Cookies["TilePreferences"].Value);
var removed = cookieInfo.FirstOrDefault(f => f.PartialName == id);
cookieInfo.Remove(removed);
//newCookie = cookieInfo;
UpdateCookie(cookieInfo, "TilePreferences", 90);
Response.StatusCode = 200;
}
and the default value and what is is "supposed" to look like when it is done:
Before:
[
{"PartialName":"_BulletinBoardTile","TileOrder":0},
{"PartialName":"_TimeCardTile","TileOrder":1},
{"PartialName":"_FeedbackTile","TileOrder":2},
{"PartialName":"_CouncilTile","TileOrder":3},
{"PartialName":"_EventsTile","TileOrder":4}
]
After(intention):
[
{"PartialName":"_BulletinBoardTile","TileOrder":0},
{"PartialName":"_TimeCardTile","TileOrder":1},
{"PartialName":"_FeedbackTile","TileOrder":2},
{"PartialName":"_CouncilTile","TileOrder":3}
}
any help is appreciated.
This code for updating the order in the file works with no issues:
public void UpdateTileOrder(string jsonString)
{
List<string> TileList = JsonConvert.DeserializeObject<List<string>>(jsonString);
var cookieInfo = new List<TileInfo>();
var i = 0;
foreach (var item in TileList)
{
if (!string.IsNullOrWhiteSpace(item))
{
var tile = new TileInfo
{
PartialName = item,
TileOrder = i
};
cookieInfo.Add(tile);
i++;
}
}
UpdateCookie(cookieInfo, "TilePreferences", 90);
}
I am making a shopping cart and for keeping track of the cart I have a session which contains a list of product view models.
This is the action method for adding to cart:
public ActionResult AddToCart(string id)
{
List<CartVM> cartVMList = new List<CartVM>();
CartVM cartVM = new CartVM();
int productId = Int32.Parse(id);
Db db = new Db();
var result = db.Products.FirstOrDefault(x => x.Id == productId);
decimal price = result.Price;
cartVM.ProductId = productId;
cartVM.Quantity = 1;
cartVM.Price = price;
if (Session["cart"] != null)
{
cartVMList = (List<CartVM>)Session["cart"];
cartVMList.Add(cartVM);
}
else
{
cartVMList.Add(cartVM);
}
Session["cart"] = cartVMList;
//return Content(id);
return RedirectToAction("Index", "ShoppingCart");
}
It works when adding new products, so e.g. if I add 5 new products the session will contain a list of 5 products, but how do I edit and delete a specific view model from the list, based on for example the ProductId ?
I haven't tested it, but the following should work. All you need to do is grab the cart list like you did when adding to cart. Instead of adding a new item, you just edit the object in the list or remove it from the list.
Technically, unless Session does something special, you shouldn't need to re-save the list to the Session if you got it from the session, since a list is a reference type.
public ActionResult EditCartItem(string id, int quantity, decimal price)
{
if (Session["cart"] != null)
{
var cartVMList = (List<CartVM>) Session["cart"];
var itemToEdit = cartVMList.FirstOrDefault(cartVM => cartVM.Id == id);
if(itemToEdit == null)
return this.HttpNotFound();
itemToEdit.Quantity = quantity;
itemToEdit.Price = price;
}
}
public ActionResult RemoveFromCart(string id)
{
if (Session["cart"] != null)
{
var cartVMList = (List<CartVM>) Session["cart"];
var itemToRemove = cartVMList.FirstOrDefault(cartVM => cartVM.Id == id);
if(itemToRemove == null)
return this.HttpNotFound();
cartVMList.Remove(itemToRemove);
}
}
I am building an restaurantfinder website with EPiServer and I'm using EPiFind to search on the site. I've encountered a problem though. I'm trying to facet a pagetype in the pagetree, although I'm only searching in one specific pagetype. My goal is to be able to print out the titles of the pagetype. So if I search for example Sweden, all cities that's in the pagetree should be listed with their names in the facet.
My code:
if (query == null && tags == null && cities == null)
{
return View();
}
var q = SearchClient.Instance.Search<RestaurantPage>()
.For(query)
.TermsFacetFor(x => x.CityPage.HeadLine);
if (!string.IsNullOrWhiteSpace(cities))
{
q = q.Filter(x => x.HeadLine.MatchCaseInsensitive(cities));
}
var results = q.Select(x => new SearchHit
{
Title = x.HeadLine,
Url = x.LinkURL,
Tag = x.Tags,
Adress = x.Adress,
Latitude = x.Latitude,
Longitude = x.Longitude,
Image = x.RestaurantImage
}).GetResult();
ViewBag.Query = query;
ViewBag.Id = results.ProcessingInfo.ServerDuration;
ViewBag.Hits = results.TotalMatching;
var facets = new List<FacetResult>();
var testFacet = (TermsFacet)results.Facets["CityPage.HeadLine"];
var testLinks = new FacetResult("Cities", testFacet.Terms.Select(x => new FacetLink
{
Text = x.Term,
Count = x.Count,
}));
facets.Add(testLinks);
ViewBag.Filters = new List<FacetLink>();
if (!string.IsNullOrEmpty(tags))
{
ViewBag.Filters.Add(new FacetLink
{
Text = tags,
Url = Url.QueryBuilder(currentPage.ContentLink).AddSegment("?query=" + query).ToString()
});
}
return View(new SearchResult(results, query) {Facets = facets});
In order to retrieve the facets, you could do:
results.TermsFacetFor<RestaurantPage>(x => x.CityPage.HeadLine)