Session variable returning null - c#

I have a login page and I tried storing some data in my sessions but when I run the project it gives me this error as you see in screenshots:
I tried to debug my code as you see in screenshot and its show me Both No_ and E_mail is null even though I checked my database and those columns. No_ and E_mail both have data:
The Code in Controller:
[HttpPost]
public ActionResult Login(string Mail)
{
using (DataContext db = new DataContext())
{
ED_data_A_S_Contact con = new ED_data_A_S_Contact();
ED_data_A_S_Contact_Business_Relation cb = new ED_data_A_S_Contact_Business_Relation();
var user = from cbr in db.Contact_Business_Relation
join c in db.Contact
on cbr.Contact_No_ equals c.Company_No_ into f
from c in f.DefaultIfEmpty()
//where c.E_Mail == Mail
select new
{
Mail = c.E_Mail
};
if (user != null)
{
Session["No_"] = cb.No_.ToString();
Session["Email"] = con.E_Mail.ToString();
FormsAuthentication.SetAuthCookie(Mail, false);
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Kunde nr er ikke gyldig");
}
}
return View();
}
public ActionResult LoggedIn()
{
if (Session["No_"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}
Contact_Business_Relation :
public string No_ { get; set; }
Contact:
public string E_Mail { get; set; }
The Code in view:
#model ED_data_A_S_Contact
<div class="login-wrap">
<div class="login-html">
<input id="tab-1" type="radio" name="tab" class="sign-in" checked><label for="tab-1" class="tab">Log ind</label>
<input id="tab-2" type="radio" name="tab" class="sign-up"><label for="tab-2" class="tab"></label>
<form class="login-form" method="POST" enctype="multipart/form-data" action="/Account/Login/">
#*#Html.AntiForgeryToken()*#
<div class="sign-in-htm">
<div class="group">
<label for="No_" class="label">Kunde ID</label>
<input style="color:black;" id="Email" name="Mail" value="" required="" type="email" placeholder="Kunde ID ..." class="input">
<button style="float: right;margin-top: -36px; background: transparent; border: none;margin-right: 11px;" type="button" id="eye">
<img src="https://cdn0.iconfinder.com/data/icons/feather/96/eye-16.png" alt="eye" />
</button>
#*#Html.ValidationMessageFor(u => u.CustomerID)*#
</div>
<div class="group">
<input type="submit" class="button" value="Log på">
</div>
<span style="color:#dadada">#*#Html.ValidationSummary(true)*#</span>
<div class="hr"></div>
<div class="foot-lnk">
<a target="_blank" href="#">Problem med login?</a>
</div>
</div>
</form>
</div>
</div>
Can anyone direct me in the right direction? thx

ED_data_A_S_Contact_Business_Relation cb = new ED_data_A_S_Contact_Business_Relation();
You don't actually seem to set the properties of this object anywhere before accessing them. All you do is new the object. All the properties have their default values.
Perhaps you should be accessing user.Mail? In which case you should also set the other properties also.
Try this:
// Populate the user variable so we can use it below to set session variables
var query = from cbr in db.Contact_Business_Relation
join c in db.Contact
on cbr.Contact_No_ equals c.Company_No_ into f
from c in f.DefaultIfEmpty()
where c.E_Mail == Mail
select new
{
Mail = c.E_Mail,
No = c.No // Or whatever the relevant property is in c or cbr
};
var user = query.FirstOrDefault();
if (user != null)
{
Session["No_"] = user.No.ToString();
Session["Email"] = user.Mail.ToString();
FormsAuthentication.SetAuthCookie(user.Mail, false);
return RedirectToAction("Index");
}

Related

asp.net mvc getting data from textbox on view back to stored procedure to edit record

I am new to ASP.NET but have done 20 years of desktop dev. I have a Customer class with fields CustId, CustName, CustNotes.
I have a view called CustView that has some input boxes that are to be pre-populated with customer details from a previous view using the CustID.
I can show the customer details in the text boxes but I cannot get the user edited textboxes (ie the user changes the name of a customer) back to a stored procedure in an Action.
I use a DB class called Cust1DBHandle to call the stored procedure. I have set up 3 buttons and 3 actions in a bid to get any of them to work, either by passing variables or using RequestString but nothing works.
Question #1: how can I pass the new text values back as either global variables, variables in the action or using a datamodel?
Question #2: in the CustViewDBHandle, I populate a list of the results. Is that the correct thing to do if it’s only for one row of data?
Question #3: when pressing a SAVE button that executes a stored procedure, do you have to have a return in the action in the controller?
Thanks.
Cust.cs model
public partial class Cust
{
[DisplayName("Cust ID")]
public Int32 CustID { get; set; }
[DisplayName("Customer Name")]
// [Required(ErrorMessage = "This field is required")]
public string CustName { get; set; }
[DisplayName("Customer Notes")]
public string CustNotes { get; set; }
public string ErrorMessageCust { get; set; }
}
CustView.cshtml:
#model IEnumerable<App22.Models.Cust>
#{
ViewBag.Title = "CustView";
}
<h2>#ViewBag.Title.</h2>
<h3>#ViewBag.Message</h3>
<header>
</header>
<meta name="viewport" content="width=device-width" />
<title>CustViewy</title>
<html>
<head>
</head>
<style>
th, td {
padding: 5px;
}
</style>
<body>
<p>
</p>
<p>CUSTOMER DETAILS ARE HERE</p>
<form name="1" method="post">
<fieldset>
<legend>Headline Details</legend>
<table>
#foreach (var item in Model)
{
<tr>
<td>
<label for="CustID">CustID:</label>
</td>
<td>
<input type="text" name="1CustID" value="#Html.DisplayFor(modelItem =>
item.CustID)" />
</td>
</tr>
<tr>
<td>
<label for="CustName">CustName:</label>
</td>
<td>
<input type="text" name="2CustName" value="#Html.DisplayFor(modelItem
=> item.CustName)" />
</td>
</tr>
<td>
<label for="CustNotes">Cust Notes:</label>
</td>
<td>
<input type="text" name="3CustNotes" value="#Html.DisplayFor(modelItem =>
item.CustNotes)" />
</td>
<tr>
<td></td>
<td>
<input type="submit" name="action:Save1" value="Save" />
<button style="background-color:red" type="button" name="tree0"
class="btn btn-primary" onclick="location.href='#Url.Action("SaveCust0","Cust1")'">
SAVE0 »
</button>
<button style="background-color:blue" type="button" name="tree1"
class="btn btn-primary" onclick="location.href='#Url.Action("SaveCust1","Cust1",new { CustyIDSave = item.CustID , CustyNameSave = item.CustName })'">
SAVE1 »
</button>
<button style="background-color:green" type="button" name="tree2" class="btn btn-primary" onclick="location.href='#Url.Action("SaveCust2","Cust1")'">
SAVE2 »
</button>
</td>
<td>
</td>
</tr>
}
</table>
</fieldset>
</form>
</body>
</html>
Cust1Controller.cs:
public class Cust1Controller : Controller
{
public ActionResult SaveCust0()
{
string message = "";
message = Request.Form["CustName"].ToString();
return Content(message);
CustViewDBHandle dbhandle = new CustViewDBHandle();
ModelState.Clear();
dbhandle.SaveCust(Convert.ToInt32(Request.Form["CustID"]),
Request.Form["CustName"].ToString());
}
public ActionResult SaveCust1(int CustyIDSave, string CustyNameSave)
{
CustViewDBHandle dbhandle = new CustViewDBHandle();
ModelState.Clear();
dbhandle.SaveCust(CustyIDSave, CustyNameSave);
return null;
}
[HttpPost]
public ActionResult SaveCust2(int CustyIDSave, string CustyNameSave)
{
CustViewDBHandle dbhandle = new CustViewDBHandle();
ModelState.Clear();
dbhandle.SaveCust(CustyIDSave, CustyNameSave);
return null;
}
// GET: Cust1
public ActionResult Index()
{
Cust1DBHandle dbhandle = new Cust1DBHandle();
ModelState.Clear();
return View("~/Views/Cust/Cust1.cshtml",dbhandle.GetCust(""));
// return View("~/Views/Cust/Cust1.cshtml"); //This works
}
[HttpGet]
public ActionResult Reload(string tree)
{
//tree = "Breaker2";
Cust1DBHandle dbhandle = new Cust1DBHandle();
ModelState.Clear();
return View("~/Views/Cust/Cust1.cshtml", dbhandle.GetCust(tree));
//Cust1DBHandle dbhandle = new Cust1DBHandle();
//ModelState.Clear();
//return View("~/Views/Cust/Cust1.cshtml", dbhandle.GetCust(SearchBy));
// return View("~/Views/Cust/Cust1.cshtml"); //This works
}
public ActionResult ViewCust(int CustyIDView)
{
//tree = "Breaker2";
CustViewDBHandle dbhandle = new CustViewDBHandle();
ModelState.Clear();
return View("~/Views/Cust/CustView.cshtml", dbhandle.GetCust(CustyIDView));
//Cust1DBHandle dbhandle = new Cust1DBHandle();
//ModelState.Clear();
//return View("~/Views/Cust/Cust1.cshtml", dbhandle.GetCust(SearchBy));
// return View("~/Views/Cust/Cust1.cshtml"); //This works
}
}
CustViewDBHandle.cs:
public class CustViewDBHandle
{
// ********** VIEW CUSTOMER DETAILS ********************
public List<Cust> GetCust(int CustyID)
{
GlobalVar.connection();
List<Cust> CustyChosen = new List<Cust>();
SqlCommand cmd = new SqlCommand("psv_CustView1", GlobalVar.con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CustyID", CustyID);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
GlobalVar.con.Open();
sd.Fill(dt);
GlobalVar.con.Close();
foreach (DataRow dr in dt.Rows)
{
CustyChosen.Add(
new Cust
{
CustID = Convert.ToInt32(dr["CustID"]),
CustName = Convert.ToString(dr["CustName"]),
CustNotes = Convert.ToString(dr["CustNotes"]),
});
GlobalVar.GlobCustName1 = Convert.ToString(dr["CustName"]); //This method uses
Global Var to get data to pass to form. Can pass anything that way.
}
return CustyChosen;
}
public int SaveCust(int CustyID, string CustyName)
{
GlobalVar.connection();
SqlCommand cmd = new SqlCommand("psu_CustSave1", GlobalVar.con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CustyID", CustyID);
cmd.Parameters.AddWithValue("#CustyName", CustyName);
GlobalVar.con.Open();
cmd.ExecuteNonQuery();
//SqlDataAdapter sd = new SqlDataAdapter(cmd);
//DataTable dt = new DataTable();
//sd.Fill(dt);
GlobalVar.con.Close();
return 1;
}
}
There is a lot to parse here, but what strikes me as the main part of the problem you have noted is:
a) You methods on the controller are not all decorated with HttpPost attributes.
b) The action on the form that you render will be looking for a POST endpoint with a name that matches the get
That said, you're going to find it hard to get answers for how to make this work, given that this is very non-idiomatic asp.net MVC code.
I would strongly suggest working through a few tutorials, as web dev is considerably different to windows dev, with a different set of challenges. Hopefully your experience will let you skim through that quickly.

Remove Image option in Edit Form

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>
}
}
}

How to Check the LINQ SQL / Query its NULL or Not - MVC

In my Action I have Three LINQ SQL(Join) , two of them which is bla4,bla5 it was working until i add Third SQL which is bla6 and SQL(bla6) only going to work or executed until RMAHistory table get data/value or have data in it and RMAHistory table get value/data until than user submitted the form before that all the rows is null in RMAHistory table and in my LINQ SQL (bla6) i have Join with RMAHistory and beacuse i have interesting one column of that table.
Here is my question how can i check if SQL (bla6) its null than run/execute bla4,bla5 and than return view and if SQL(bla6) its not null than run/execute (bla4,bla5,bla6) and in the return view.
I have tried to check if modal its null or not both in view and Controller ,but i get Object reference is not set to an instance of an object and it's beacuse rmah.AntalRMA is null.
Can anyone help me or point me in the right direction!
Thanks in advance :)
Controller:
public ActionResult RMA(RMAHistory oodvm ,string id, string Varenummer, string OrdreNo)
{
var bla6 = (from sil in data.Sales_Invoice_Line
join rmah in data.RMA_History on sil.Document_No_ equals rmah.Fakturnummer
where sil.Document_No_ == id
select new RMAHistory.SingelRMAAntal
{
TotalRMA = rmah.AntalRMA
});
var col2 = data.Sales_Shipment_Line.Where(t => t.Order_No_ == OrdreNo).Where(t => t.No_ == Varenummer).Select
(t => new
{
No_ = data.Sales_Invoice_Header.Where(or => or.Order_No_ == OrdreNo).FirstOrDefault().No_,
Line = t,
Serial = data.Item_Ledger_Entry.Where(ledger => ledger.Document_No_ == t.Document_No_).Where(ledger => ledger.Document_Line_No_ == t.Line_No_).ToList(),
TrackAndTrace = data.Track_and_Trace.Where(track => track.Shipping_No_ == t.Document_No_).Select(tr => new { traceNR = tr.Track_and_Trace, tracePath = tr.Track_and_trace_path, Agent = tr.Shipping_agent }).FirstOrDefault()
});
var bla4 = col2.Select(t =>
new RMAHistory.OrdreRMA
{
//Select something
});
var bla5 = (from sih in data.Sales_Invoice_Header
join sil in data.Sales_Invoice_Line on sih.No_ equals sil.Document_No_
join item in data.Item on sil.No_ equals item.No_
join itemcat in data.ItemCategory on item.Item_Category_Code equals itemcat.Code
where sil.Document_No_ == id
&&
sil.No_ == Varenummer
&&
sih.Order_No_ == OrdreNo
select new RMAHistory.InvoiceOrdreLineSingel
{
//Select something
});
oodvm.OrdreRMAs = bla4.FirstOrDefault();
oodvm.InvoiceDetailsSingelLine = bla5.FirstOrDefault();
oodvm.SingelRMAAntals = bla6.FirstOrDefault();
return View(oodvm);
}
RMAHistory ViewModel:
public class RMAHistory
{
public SingelRMAAntal SingelRMAAntals { get; set; }
public class SingelRMAAntal
{
public SingelRMAAntal()
{
}
public SingelRMAAntal(string TotalRMA)
{
this.TotalRMA = TotalRMA;
}
public string TotalRMA { get; set; }
}
}
View:
#using NameSpace.Models
#model RMAHistory
<div class="content">
<form id="RMAForm">
<input type="text" id="Kundenavn" value="#Model.InvoiceDetailsSingelLine.Kundenavn">
<br/>
<input id="Ordrenummer" type="text" value="#Model.InvoiceDetailsSingelLine.Ordrenummer">
<br/>
if (Model.SingelRMAAntals.TotalRMA == null)
{
<div style="display:none;" class="col-md-3">
<input name="Antal_RMA" id="Antal_RMA" value="#Model.SingelRMAAntals.TotalRMA">
</div>
}
else
{
<div class="col-md-3">
<input name="Antal_RMA" id="Antal_RMA" value="#Model.SingelRMAAntals.TotalRMA">
</div>
}
</form>
</div>
Change your view to look like below
#using NameSpace.Models
#model RMAHistory
<div class="content">
<form id="RMAForm">
<input type="text" id="Kundenavn" value="#Model.InvoiceDetailsSingelLine.Kundenavn">
<br/>
<input id="Ordrenummer" type="text" value="#Model.InvoiceDetailsSingelLine.Ordrenummer">
<br/>
if (Model != null)
{
if (Model.SingelRMAAntals != null)
{
if (Model.SingelRMAAntals.TotalRMA == null)
{
<div style="display:none;" class="col-md-3">
<input name="Antal_RMA" id="Antal_RMA" value="#Model.SingelRMAAntals.TotalRMA">
</div>
}
else
{
<div class="col-md-3">
<input name="Antal_RMA" id="Antal_RMA" value="#Model.SingelRMAAntals.TotalRMA">
</div>
}
}
}
</form>
</div>

C#: HttpCookie Content Setted in Index Page and then desapeared on all over the WebSite

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.

Filling Data For Partial View MVC

We're developing news website we're confused with some concept of usage. I'd like to ask and know better if possible. We've a homepage which may contain a lot of models at once so we're separating our homepage to partial views and we're planning to feed them with the appropriate models.
In one partial we're enumerating in categories that are not marked as deleted and we've two types of categories. One of them displays the latest post and the other displays 4 posts at once. We've achieved this actually but as i've mentioned we would like to know if there is a better way or if we're doing anything wrong because right now we're keeping the connection to the context open until the partial is rendered.
Here is the code for views
Partial View Code (CategoryRepeater.cshtml)
#using SosyalGundem.WebUI.DatabaseContext;
#{
var categoryList = new List<PostCategories>();
var db = new SosyalGundemDb();
categoryList = db.PostCategories.Include("Posts").Where(x => !x.IsDeleted).ToList();
}
#for (int i = 0; i < categoryList.Count; i++)
{
if (i % 3 == 0 || i == 0)
{
#Html.Raw("<div class=\"row-fluid spacer\">")
}
var category = categoryList[i];
if (category.PostCategoryType == 1)
{
<div class="span4">
<h3 class="title"><span>#category.PostCategoryName</span></h3>
#{
var article = category.Posts.FirstOrDefault();
if (article != null)
{
<article class="post">
<div class="entry clearfix">
<div class="span6">
<a href="#" title="Permalink to Suspen disse auctor dapibus neque pulvinar urna leo" rel="bookmark">
<img width="225" height="136" src="#Url.Content("~/Content/uploadedimages/" + article.Media.ToList()[0].MediaContent )" alt="shutterstock_70184773" />
</a>
</div>
<div class="span6">
<h4 class="smallnewstitle">#article.PostTitle</h4>
<p>#(article.PostSummary.Length > 100 ? article.PostSummary.Substring(0, 100) : article.PostSummary)</p>
<div class="meta">
<span class="date">#article.PostDate.ToString("MMMM dd, yyyy")</span>
</div>
</div>
</div>
</article>
}
}
</div>
}
else
{
<div class="video-box widget span4">
<h3 class="title"><span>#category.PostCategoryName</span></h3>
#{
int cati = 0;
var firstPost = category.Posts.OrderByDescending(x => x.PostDate).FirstOrDefault();
}
#if (firstPost != null)
{
<h4 class="smallnewstitle">#firstPost.PostTitle</h4>
<p>#(firstPost.PostSummary.Length > 100 ? firstPost.PostSummary.Substring(0, 100) : firstPost.PostSummary) </p>
<ul>
#foreach (var item in category.Posts.OrderByDescending(x => x.PostDate))
{
if (cati <= 3)
{
<li>
<a href="#" title="#item.PostTitle" rel="bookmark">
<img width="225" height="136" src="#Url.Content("~/Content/images/dummy/shutterstock_134257640-225x136.jpg")" alt="shutterstock_134257640" />
</a>
</li>
}
else
{
break;
}
cati++;
}
</ul>
}
</div>
}
if (i % 3 == 0 && i != 0)
{
#Html.Raw("</div>")
}
}
#{
db.Dispose();
}
Separate your concerns. You can see this project for start: http://www.codeproject.com/Tips/617361/Partial-View-in-ASP-NET-MVC
Controller
#using SosyalGundem.WebUI.DatabaseContext;
public ActionResult SomeAction()
{
var model = new CategoriesModel
{
NotDeletedCategories = db.PostCategories.Include("Posts").Where(x => !x.IsDeleted).ToList(),
DeletedCategories = db.PostCategories.Include("Posts").Where(x => x.IsDeleted).ToList()
};
return View(model);
}
Model
public class CategoriesModel
{
public List<PostCategories> NotDeletedCategories {get;set;}
public List<PostCategories> DeletedCategories {get;set;}
};
View
#model CategoriesModel
#Html.RenderPartial("DeletedCategories", Model.DeletedCategories)
#Html.RenderPartial("NotDeletedCategories", Model.NotDeletedCategories)
Hi Jinava,
I would suggest bind Model to the View,
Like,
public ActionResult CategoryRepeater()
{
var multiViewModel = new MultiViewModelModel
{
ModelForParialView1= new XYZ(),
ModelForParialView2= new PQR()
};
return View(model);
}
For the View
#model MultiViewModelModel
And then PAss the views with the MultiViewModelModel.ModelForParialView1 and MultiViewModelModel.ModelForParialView2
You can perform all the model operations on the view.
And at the controller level perform all the database operations and release the database connection there itself no need to get that on the view.
Hope this explanation helps you.

Categories