I am trying to change the file name of images to the value that I posted in the input box username. The files are getting uploaded to the server and also, after overriding GetLocalFileName the file name is changed from "BodyPart_(xyz)" to the original one. How do I rename them to the value that I provided in the input box?
<form name="form1" method="post" enctype="multipart/form-data" action="api/poster/postformdata">
<div class="row-fluid fileform">
<div class="span3"><strong>Username:</strong></div>
<input name="username" value="test" type="text" readonly/>
</div>
<div class="row-fluid fileform">
<div class="span3"><strong>Poster:</strong></div>
<div class="span4"><input name="posterFileName" ng-model="posterFileName" type="file" /></div>
</div>
<div class="row-fluid fileform">
<div class="span8"><input type="submit" value="Submit" class="btn btn-small btn-primary submitform" /></div>
</div>
</form>
I have stored the value that I received in the newName variable but I am confused on how to rename the file in the server.
public async Task<HttpResponseMessage> PostFormData()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
await Request.Content.ReadAsMultipartAsync(provider);
// Show all the key-value pairs.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
Trace.WriteLine(string.Format("{0}: {1}", key, val));
newName = val;
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public class MyMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public MyMultipartFormDataStreamProvider(string path)
: base(path)
{
}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
string fileName;
if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName))
{
fileName = headers.ContentDisposition.FileName;
}
else
{
fileName = Guid.NewGuid().ToString() + ".data";
}
return fileName.Replace("\"", string.Empty);
}
}
One way is to override the ExecutePostProcessingAsync method like the following:
public override async Task ExecutePostProcessingAsync()
{
await base.ExecutePostProcessingAsync();
// By this time the file would have been uploaded to the location you provided
// and also the dictionaries like FormData and FileData would be populated with information
// that you can use like below
string targetFileName = FormData["username"];
// get the uploaded file's name
string currentFileName = FileData[0].LocalFileName;
//TODO: rename the file
}
Related
I am developing a Server-Side Blazor app in which a user inputs excel files with data. The app goes over each excel file, checks if it is valid and creates output files (based on excel file content) for user to download.
There is a table that displays IEnumerable<IExcelFile>, a list of objects with following parameters: FileName, FileType, Package (not for display). I would like to call a method that iterates over each IExcelFile and take some actions for each excel (check if valid, process). When the method is running I would like FileType of each IExcelFile to indicate, on which step of the process a particular file is. e.g. When method starts all IExcelFiles have a "Queued" FileType, when one of IExcelFiles is processed it's FileType changes to "Processing", when an exception is thrown for one excel file it's FileType changes to "Error" and so on.
I am able to change those parameters just before and after running this method but not when the method is running. Below is the code:
Table:
<table class="table table-hover">
<thead>
<tr>
<th>FileName</th>
<th>FileType</th>
<th style="width: 10px;"></th>
</tr>
</thead>
<tbody>
#if (excelFiles != null && excelFiles.Count() > 0)
{
foreach (var excelFile in excelFiles)
{
<tr>
<td>#excelFile.FileName</td>
<td>#excelFile.FileType.ToString()</td>
<td>
#if (!IsLoading)
{
<button class="btn btn-close" #onclick="() => DeleteExcelFile(excelFile)"></button>
}
</td>
</tr>
}
}
else
{
<tr>
<td colspan="3">
No files provided
</td>
</tr>
}
</tbody>
</table>
Processing excel file starts when the user clicks a "Start" button:
#if (!IsLoading)
{
<div class="mb-3">
<label for="formFileMultiple" class="form-label">Select excel files from your drive</label>
#for (int i = 0; i < numberOfInputFiles; i++)
{
<InputFile #key="i" OnChange="UploadExcelFiles" multiple style="#GetInputFileStyle(i)" class="form-control" type="file" id="formFileMultiple"></InputFile>
}
</div>
#if (IsDownloadAvailable)
{
<button type="button" class="btn btn-success" #onclick="DownloadDubCards">Download</button>
<button type="button" class="btn btn-primary" #onclick="ClearExcelFileList">Clear</button>
}
else
{
<button type="button" class="btn btn-primary" #onclick="GenerateDubCards">Start</button>
<button type="button" class="btn btn-primary" #onclick="ClearExcelFileList">Clear</button>
}
}
else
{
<div class="spinner-border text-primary" role="status" style="left: 50%; position: absolute; width: 3rem; height: 3rem;">
<span class="visually-hidden">Loading...</span>
</div>
}
And the method that is processing the excel files:
private void GenerateDubCards()
{
foreach (var excelFile in excelFiles)
{
excelFile.FileType = IExcelFile.Type.Queued;
}
foreach (var excelFile in excelFiles)
{
try
{
excelFile.FileType = IExcelFile.Type.Processing;
List<IDubCardSet> tempDubCardSets = dubCardGenerator.CalculateDubCardSetsFromExcelFile(excelFile);
dubCardSets = dubCardGenerator.AddDubCardSets(tempDubCardSets);
foreach (var dubCardSet in dubCardSets.Where(dcs => dcs.DubCards.Count == 0))
{
dubCardGenerator.CreateDubCards(dubCardSet);
}
excelFile.FileType = IExcelFile.Type.Completed;
}
catch (Exception ex)
{
excelFile.FileType = IExcelFile.Type.Error;
AppLogger.GetInstance().Info(ex.Message);
Modal.Open("Something went wrong!", ex.Message);
}
}
IsDownloadAvailable = true;
}
So basically after this method runs I just see all excel files have a FileType "Complete", but when the method runs I see no other values in between (even when debugging step by step).
Additional context that I hope is irrelevant for this issue:
This is a child component but no parameters are passed from the parent to child nor are any parameters from child shared with or dependent on parent.
This components has other methods that use StateHasChanged() like deleting or adding list elements that work properly.
I tried changing method from private void to async Task, call StateHasChanged() anywhere but with no success. I tried pretty much any related solutions on Stack Overflow, but it didn't work. Any help would be much appreciated, Thanks.
I've simplified your code into a single page which I believe demonstrates what you're trying to achieve. It demonstrates the principles of using async coding and using StateHasChanged to drive re-renders. The key bit is that the backend process that gets the data has to be a yielding async process for this to work properly. The Renderer needs thread time to update the UI. Blocking processes stop that happening.
#page "/"
<h3>Async File Processing</h3>
<div class=m-2>
<button class="btn btn-primary" #onclick=GenerateDubCards>Process</button>
</div>
#foreach(var file in excelFiles)
{
<div class="m-2 p-2 #GetCss(file)">#file.Name : #file.State</div>
}
#code {
private List<ExcelFile> excelFiles = new() { new ExcelFile { Name="UK"}, new ExcelFile { Name="Spain"}, new ExcelFile { Name="Portugal"}, new ExcelFile { Name="Australia"}};
private string GetCss(ExcelFile file)
=> file.State switch
{
FileState.Complete => "bg-success text-white",
FileState.Processing => "bg-warning text-white",
FileState.Error => "bg-danger text-white",
_ => "bg-primary text-white"
};
private async Task GenerateDubCards()
{
List<Task> tasks = new List<Task>();
foreach(var file in excelFiles)
{
tasks.Add(ProcessAFile(file));
}
await Task.WhenAll(tasks.ToArray());
}
private async Task ProcessAFile(ExcelFile file)
{
file.State = FileState.Processing;
StateHasChanged();
// emulate the file work with a variable length Task Delay
await Task.Delay(Random.Shared.Next(5000));
file.State = FileState.Complete;
if (file.Name.StartsWith("S"))
file.State = FileState.Error;
StateHasChanged();
}
public class ExcelFile
{
public string Name { get; set; } = string.Empty;
public FileState State { get; set; } = FileState.None;
}
public enum FileState
{
None,
Processing,
Complete,
Error
}
}
I am trying to use ASP to upload a JSON file. However, for some strange reason, the control that I use for that only forwards the file name, but not the path.
Here's what I'm doing in my .cshtml:
<form asp-page-handler="AddDevices" method="post" >
<button
class="btn btn-default"
id="btn_add_devices"
>
Add Devices
</button>
<input type="file" name="fileNameAndPath" accept="application/JSON"/>
</form>
...and here's the function that gets called in the corresponding .cs:
public void OnPostAddDevices(string fileNameAndPath)
{
string jsonString = System.IO.File.ReadAllText(fileNameAndPath);
[Deserialization]
}
The problem is, that instead of the file name and path that I would like to arrive at that function, only the file name is passed on, so for example if I use the file selector to select the file C:/TestFiles/TestJson.json, then in the function OnPostAddDevices, the value of the parameter fileNameAndPath is only TestJson.json instead of what I would need C:/TestFiles/TestJson.json.
Naturally, that subsequently results in a FileNotFoundException.
What can I do to make the input pass on the full file name with path in this case?
Here's what I ended up doing now, and what worked to my satisfaction based on the following tutorial:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-6.0
Summed up in short:
In my index.cshtml, I added this for the upload button:
<form enctype="multipart/form-data" method="post">
<dl>
<dt>
<label asp-for="FormFile"></label>
</dt>
<dd>
<input asp-for="FormFile" type="file">
</dd>
</dl>
<input asp-page-handler="UploadDeviceFile" class="btn" type="submit" value="Upload">
</form>
In my Index.cshtml.cs, I added this for the uploading logic:
[BindProperty]
public IFormFile FormFile { get; set; }
public async Task<IActionResult> OnPostUploadDeviceFileAsync()
{
using (var memoryStream = new MemoryStream())
{
await FormFile.CopyToAsync(memoryStream);
string jsonString = Encoding.ASCII.GetString(memoryStream.ToArray());
DeviceContainer deviceContainer = JsonConvert.DeserializeObject<DeviceContainer>(jsonString);
DatabaseController.AddAll(deviceContainer.Devices);
}
return Page();
}
<div>
<div>
<div class="#(Base64Images.Count == 0 ? "block" : "hidden")">
<label for="file-upload">
<span>Upload a file</span>
<InputFile OnChange="HandleChange" id="file-upload" name="file-upload" class="sr-only" />
</label>
</div>
<div class="#(Base64Images.Count > 0 ? "block" : "hidden")">
#foreach(var image in Base64Images)
{
<img src="#image" />
}
</div>
</div>
</div>
#code {
public IReadOnlyList<IBrowserFile> BrowserFiles { get; protected set; } = new List<IBrowserFile>();
private List<string> Base64Images { get; set; } = new List<string>();
private async Task<bool> HandleChange(InputFileChangeEventArgs e)
{
IReadOnlyList<IBrowserFile> fileList;
BrowserFiles = new List<IBrowserFile> { e.File };
await BrowserFilesToBase64Images();
return true;
}
private async Task<bool> BrowserFilesToBase64Images()
{
foreach(var image in BrowserFiles)
{
if(image != null)
{
var format = "image/png";
var buffer = new byte[image.Size];
await image.OpenReadStream().ReadAsync(buffer);
Base64Images.Add($"data:{format};base64,{Convert.ToBase64String(buffer)}");
}
}
return true;
}
}
So I have this code, it's pretty simple. I want to display a preview of what the use uploads, but the preview must only be displayed after the file was selected. Likewise, I want to hide the input (but not remove it from the DOM) when there is an image loaded. But no matter what I do, Blazor won't re-render.
Base64Images.Count
Changes and I have been able to debug it. The conditions should be hit, but the HTML won't change. Is there any way to tell Blazor to re-render?
I know of StateHasChanged(), but not only that one is supposedly called in after every event, but even calling it multiple times doesn't force the re-render.
You'll have to explain what you want to happen. You have Lists, but when you handle the FileInput's OnChange, you're only getting one File (maybe).
If you want multiple files, then you'll have to set your FileInput like this:
<InputFile OnChange="HandleChange" id="file-upload" name="file-upload" class="sr-only" multiple />
And to get the collection of IBrowserFile objects, this:
BrowserFiles = e.GetMultipleFiles(maxAllowedFiles);
Here's my test code based on what you've given us. It works, so we're missing something obvious.
#page "/Images"
<div class="#(Base64Images.Count > 0 ? "block" : "hidden")">
#foreach (var image in Base64Images)
{
<h4>Images goes here</h4>
<img src="#image" />
}
</div>
#if (!_hasImages)
{
<div>
<InputFile OnChange="#OnInputFileChange" multiple />
</div>
}
else
{
<div>
#foreach (var image in Base64Images)
{
<h4>More Images goes here</h4>
<img src="#image" />
}
</div>
}
<button class="btn btn-dark" #onclick="() => Click()"> Click</button>
#code {
List<string> Base64Images = new List<string>();
private bool _hasImages => Base64Images != null && Base64Images.Count > 0;
void Click()
{
Base64Images.Add("Bye");
}
private async Task OnInputFileChange(InputFileChangeEventArgs e)
{
await Task.Delay(1000);
Base64Images.Add("Bye");
}
}
I want to delete image in edit form and to show the upload file option .How can I achieve this using Ajax since I'm using tab panes for multiple forms.
Here is my code,
Biodata.cshtml
<div class="form-group">
<label class="control-label-staff"><b>Photo</b></label>
#if (Model.ImageFiles != null)
{
foreach (var item in Model.ImageFiles)
{
if (item.Name.Substring(0, 2) == "IM")
{
<span class="control-label-staff">
<img src="~/Documents/EmployeeAttachments/#Request.Query["EmpID"].ToString()/#item.Name" width="70px" height="70px" />
</span><br/>
<a asp-page-handler="RemoveImage" data-ajax="true" data-ajax-method="post" data-ajax-complete="RemoveImageCompleted">Delete</a>
}
}
}
#if (Model.ImageFiles == null)
{
<input type="file" asp-for="StaffPhoto" class="form-control-staff" accept="image/*" style="border:1px solid white;" />
}
</div>
Its not calling the asp-page-handler method. Directly executing the ajax method.
function RemoveImageCompleted(event) {
if (event.responseText != "") {
$("#Biodata").html(event.responseText);
} else {
alert("Image Has Been Deleted Successfully");
$.ajax({
url:rootPath + "/Staff/Onboarding/Biodata",
type: "get",
success: function (result) {
$("#Biodata").html(result);
$('a[href="#Biodata"]').tab('show');
}
})
}
}
This is my asp-page-handler method in BioData.cshtml.cs
public async Task<IActionResult> OnPostRemoveImageAsync()
{
string filename = Request.Form["filename"];
if (filename != null)
{
var Folder = StaffBioData.EmpID.ToString();
string filedel = Path.Combine(_env.WebRootPath, "Documents/EmployeeAttachments", Folder, filename);
FileInfo fi = new FileInfo(filedel);
if (fi != null)
{
System.IO.File.Delete(filedel);
fi.Delete();
}
}
return new OkResult();
}
Any help would be appreciated.Thanks.
Links are GET requests. You cannot post via a link; that is what forms are for. You'd need something like:
#if (Model.ImageFiles != null)
{
foreach (var item in Model.ImageFiles)
{
if (item.Name.Substring(0, 2) == "IM")
{
#*<a asp-page-handler="RemoveImage" data-ajax="true" data-ajax-method="post" data-ajax-complete="RemoveImageCompleted">Delete</a>*#
<form method="post" asp-page-handler="RemoveImage" data-ajax="true" data-ajax-method="post" data-ajax-complete="RemoveImageCompleted">
<input type="submit" value="delete" />
</form>
}
}
}
I'm facing an issue using HttpCookie.
I'm building an Ecommerce and I'm trying to set Cookies for my Website.
There are three Cookies defined as describe bellow:
private static string cookienameCampanha = "WLC-Ecommerce-Campanha";
private static string cookienameUsuario = "WLC-Ecommerce-Usuario";
private static string cookienameRodape = "WLC-Ecommerce-Rodape";
All of then is used when HttpCookie is instantiated as bellow:
HttpCookie cookiehelper = new HttpCookie(cookienameCampanha);
HttpCookie cookiehelper = new HttpCookie(cookienameUsuario);
HttpCookie cookiehelper = new HttpCookie(cookienameRodape);
When user access index page for my Ecommerce, all those Cookies were setted. And they have specific definitions.
The third one, cookienameRodape, is used for setting content in footer and my web site shows those contents.
But after index page got fully reload and my footer listed all content, My Web Browser shows that all cookienameRodape content was erased and when I redirect the page to any other pages inside my site, all content is empty.
Something is weird, in DevTools using Chrome I can see other two Cookies Content setted and not erased, but "WLC-Ecommerce-Rodape" is not there even all content is listed in index page.
See the print below:
We can check My Index page and all content in my footer:
But when I try to navegate through my webSite, suddenly all content desapeared:
Additionaly, When always returned to index page, all Cookies are setted again and then all content inside footer are listed.
I tryed to search all over the SO and none of then suited me.
All Cookies are removed when user logged out. There is no any moment this happend.
After All content came from DataBase, Footer Contents were defined as below:
public static class AuxiliarCookieBLL
{
public static List<CampanhaInstitucionalModel> GetCampanhaInstitucional()
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaInstitucional")))
{
List<CampanhaInstitucionalModel> CampanhaInstitucional = JsonConvert.DeserializeObject<List<CampanhaInstitucionalModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaInstitucional")));
return CampanhaInstitucional;
}
else
return new List<CampanhaInstitucionalModel>();
}
public static void SetCampanhaInstitucional(List<CampanhaInstitucionalModel> CampanhaInstitucional)
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (CampanhaInstitucional != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaInstitucional);
cookiehelper.AddToCookie("CampanhaInstitucional", HttpUtility.UrlEncode(campanha));
}
}
public static List<CampanhaAtendimentoModel> GetCampanhaAtendimento()
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaAtendimento")))
{
List<CampanhaAtendimentoModel> CampanhaAtendimento = JsonConvert.DeserializeObject<List<CampanhaAtendimentoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaAtendimento")));
return CampanhaAtendimento;
}
else
return new List<CampanhaAtendimentoModel>();
}
public static void SetCampanhaAtendimento(List<CampanhaAtendimentoModel> CampanhaAtendimento)
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (CampanhaAtendimento != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaAtendimento);
cookiehelper.AddToCookie("CampanhaAtendimento", HttpUtility.UrlEncode(campanha));
}
}
public static List<CampanhaCentralAtendimentoModel> GetCampanhaCentralAtendimento()
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaCentralAtendimento")))
{
List<CampanhaCentralAtendimentoModel> CampanhaCentralAtendimento = JsonConvert.DeserializeObject<List<CampanhaCentralAtendimentoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaCentralAtendimento")));
return CampanhaCentralAtendimento;
}
else
return new List<CampanhaCentralAtendimentoModel>();
}
public static void SetCampanhaCentralAtendimento(List<CampanhaCentralAtendimentoModel> CampanhaCentralAtendimento)
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (CampanhaCentralAtendimento != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaCentralAtendimento);
cookiehelper.AddToCookie("CampanhaCentralAtendimento", HttpUtility.UrlEncode(campanha));
}
}
public static List<CampanhaCertificadoModel> GetCampanhaCertificado()
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaCertificado")))
{
List<CampanhaCertificadoModel> CampanhaCertificado = JsonConvert.DeserializeObject<List<CampanhaCertificadoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaCertificado")));
return CampanhaCertificado;
}
else
return new List<CampanhaCertificadoModel>();
}
public static void SetCampanhaCertificado(List<CampanhaCertificadoModel> CampanhaCertificado)
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (CampanhaCertificado != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaCertificado);
cookiehelper.AddToCookie("CampanhaCertificado", HttpUtility.UrlEncode(campanha));
}
}
public static List<CampanhaFormaPagamentoModel> GetCampanhaFormaPagamento()
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaFormaPagamento")))
{
List<CampanhaFormaPagamentoModel> CampanhaFormaPagamento = JsonConvert.DeserializeObject<List<CampanhaFormaPagamentoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaFormaPagamento")));
return CampanhaFormaPagamento;
}
else
return new List<CampanhaFormaPagamentoModel>();
}
public static void SetCampanhaFormaPagamento(List<CampanhaFormaPagamentoModel> CampanhaFormaPagamento)
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (CampanhaFormaPagamento != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaFormaPagamento);
cookiehelper.AddToCookie("CampanhaFormaPagamento", HttpUtility.UrlEncode(campanha));
}
}
}
And now I can show my script footer page when I call all content and list then:
<div class="limite-layout">
<nav>
<ul class="col-xs-12 no-padding" id="navFooter">
<li class="col-md-2 institucional">
<div>
#{
rodape.Rodape.ListInstitucional = BLL.AuxiliarCookieBLL.GetCampanhaInstitucional();
if (rodape.Rodape.ListInstitucional.Count > 0)
{
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Institucional</h6>
<ul id="Institucional" class="collapse">
#foreach (var item in rodape.Rodape.ListInstitucional)
{
#*<li>#item.Nome</li>*#
<li>#item.Nome</li>
}
</ul>
}
}
</div>
</li>
<li class="col-md-2 atendimento">
<div>
#{
rodape.Rodape.ListAtendimento = BLL.AuxiliarCookieBLL.GetCampanhaAtendimento();
if (rodape.Rodape.ListAtendimento.Count > 0)
{
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Atendimento</h6>
<ul id="Atendimento" class="collapse">
#foreach (var item2 in rodape.Rodape.ListAtendimento)
{
<li>#item2.Nome</li>
}
</ul>
}
}
</div>
</li>
<li class="col-md-2 central-atendimento">
<div>
#{
rodape.Rodape.ListCentralAtendimento = BLL.AuxiliarCookieBLL.GetCampanhaCentralAtendimento();
if (rodape.Rodape.ListCentralAtendimento.Count > 0)
{
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Central de Atendimento</h6>
<ul id="CentralAtendimento" class="collapse">
#foreach (var item3 in rodape.Rodape.ListCentralAtendimento)
{
<li>#item3.Nome</li>
}
</ul>
}
}
</div>
</li>
<li class="col-md-3">
<div class="certificados">
#{
rodape.Rodape.ListCertificado = BLL.AuxiliarCookieBLL.GetCampanhaCertificado();
if (rodape.Rodape.ListCertificado.Count > 0)
{
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Certificados</h6>
<ul id="Certificados" class="collapse list-horizontal">
#foreach (var item5 in rodape.Rodape.ListCertificado)
{
#*<li><img alt="#item5.Nome" src="#item5.Descricao" /></li>*#
<li><img alt="#item5.Nome" src="~/Content/img/conteudo/certificados/ligodaddy.png" /></li>
<li><img alt="#item5.Nome" src="~/Content/img/conteudo/certificados/clearsale_logo.jpg" /></li>
<li><img alt="#item5.Nome" src="~/Content/img/conteudo/certificados/ABComm.png" /></li>
}
</ul>
}
}
</div>
<div class="pagamentos">
#{
rodape.Rodape.ListFormaPagamento = BLL.AuxiliarCookieBLL.GetCampanhaFormaPagamento();
if (rodape.Rodape.ListFormaPagamento.Count > 0)
{
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Formas de Pagamento</h6>
<ul id="FormaPagamento" class="collapse">
#foreach (var item4 in rodape.Rodape.ListFormaPagamento)
{
#*<li><img alt="Formas de Pagamento" src="#item4.URL" /></li>*#
<li><img alt="Formas de Pagamento" src="#item4.URL" /></li>
#*<li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/mastercard.jpg" title="Mastercard"/></li>
<li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/itau.jpg" title="Itaú"/></li>
<li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/elo.jpg" title="Elo"/></li>
<li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/boleto.jpg" title="Boleto"/></li>*#
}
</ul>
}
}
</div>
#if(BLL.AuxiliarCookieBLL.GetExibirRegulamento() == true)
{
<div class="footer-social">
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Redes Sociais</h6>
<ul id="Social" class="collapse list-horizontal">
<li>
<i class="icon icon-facebook"></i>
<i class="icon icon-twitter2"></i>
<i class="icon icon-gplus"></i>
</li>
</ul>
<div class="clearfix"></div>
</div>
}
</li>
<li class="col-md-3 ofertas">
<div>
<h6>Receba ofertas exclusivas no seu e-mail</h6>
<div class="form-group col-xs-12 no-padding">
<input type="text" name="Email" id="txtEmailNewsLetter" placeholder="Digite seu e-mail" />
</div>
<div class="form-group col-md-8 input-left">
<input type="text" name="Nome" id="txtNomeNewsLetter" placeholder="Digite seu nome" />
</div>
<div class="form-group col-md-4 no-padding container-btn-enviar text-right">
Enviar
</div>
<p id="erroNewsLetter" class="display-none no-margin-top">Verifique os campos digitados!</p>
<p id="msgOkNewsLetter" class="display-none no-margin-top">E-mail cadastrado.</p>
<p id="msgErroRequest" class="display-none no-margin-top">Erro ao cadastrar. Por favor tente novamente.</p>
<div class="clearfix"></div>
</div>
</li>
</ul>
</nav>
<div class="clearfix"></div>
</div>
EDIT
Here is CookieHelper code content:
There are two constructors and Property
//Constructors
public CookieHelper(String CookieName)
{
myCookieName = CookieName;
}
public CookieHelper(String CookieName, DateTime ExpiresDate)
{
myCookieName = CookieName;
dtExpires = ExpiresDate;
}
//Property
private static HttpCookie myCookie
{
get
{
return HttpContext.Current.Request.Cookies[myCookieName] != null ? HttpContext.Current.Request.Cookies[myCookieName] : NewCookie();
}
set
{
HttpContext.Current.Response.Cookies.Add(value);
}
}
And here is basic methods:
public void AddToCookie(String FieldName, String Value)
{
HttpCookie myHttpCookie = myCookie;
myHttpCookie[FieldName] = Value;
myCookie = myHttpCookie;
}
public void RemoveCookie()
{
HttpCookie myHttpCookie = myCookie;
myHttpCookie.Value = null;
myHttpCookie.Expires = DateTime.Now.Date.AddDays(-1);
myCookie = myHttpCookie;
}
private static HttpCookie NewCookie()
{
HttpCookie newcookie = new HttpCookie(myCookieName);
if(dtExpires != null)
newcookie.Expires = (DateTime)dtExpires;
HttpContext.Current.Response.Cookies.Add(newcookie);
return newcookie;
}
What could be happening?
All content inside this Cookie worked fine, and suddenly all Browsers are not stored this specific one.
Can any one help me with this problem?
If needs any further information, please advise me.
Not sure about your code in CookieHelper but I can't see that you'r setting an expiration or adding the cookie to the response. Those are two very important parts to using cookies so if they are missing, try to do something like this
public static void SetCampanhaInstitucional(List<CampanhaInstitucionalModel> CampanhaInstitucional)
{
if (CampanhaInstitucional != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaInstitucional);
HttpCookie theCookie = new HttpCookie(cookienameRodape, campanha);
theCookie.Expires.AddDays(7); //Keep the cookie alive for 7 days
HttpContext.Response.Cookies.Add(theCookie); //add the cookie to the response
//alternatively you could also use
//HttpContext.Response.SetCookies(theCookie);
}
}
If your having trouble with using HttpContext.Response.Cookies.Add(theCookie); you might need to set the cookie using Response.SetCookie(theCookie) as per This answer to a cookie problem
Also, how much data are you storing?
Cookies are not ment to store alot of data and most browsers support up to 4096 bytes or 4kb. This is however for all cookies on the domain, so if you have 2 cookies using the 4kb, then adding another cookie will result the loss off cookies.
I can see from the screenshot that you are not using all of the available space, but as the Rodape cookie is not present, I have now idea of how big than one might be. Try just adding the Rodape cookie and see if it persists and check the size of it.
There are numerous possible causes for what you're seeing. To find the specific cause for your case, I would start by setting breakpoints in the code in any place where the value of the cookie gets set or reset. By running the code in a debugger, you can see if that code gets called at unexpected times. Repeat the steps to reproduce the problem, taking note of any unexpected calls to the code that change the cookie value. See what this reveals.