MVC newbie MVC newbie -4 years ago 102
Ajax Question

MVC global List was reset after ajax post back

I have this piece of code that check for duplicates before adding it to the list.
However,everytime after ajax post call. the list will be return reset to 0.

Anyway to maintain the data in the list?

Javascript :

function addbarcode() {
debugger
var artno = $("#scanner").val();
$.ajax({
url: '@Url.Action("Addbarcode", "Home")',
type: 'POST',
datatype: 'json',
data: { "text": artno },
success: function (data) {

$("#msg").html(data);

},
error: function (err) {

document.getElementById('msg').innerHTML = err;
}
});
}


**Controller*:*

List<Barcode> getListBarcode=new List<Barcode>();
public string Addbarcode(string text) {
Barcode barcode = new Barcode();
barcode.original = text;
barcode.Article= text.Substring(10, 5);
barcode.serial= text.Substring(text.Length - 14);
if (getListBarcode.Contains(barcode)==false)
{
getListBarcode.Add(barcode);
Session["barcodelist"] = getListBarcode;
string total= "Total of :" + getListBarcode.Count;
return total;
}
else
{
return "Duplicates";
}

}


Edited 1
Delay in assigning when the code run using getter and setter

public List<Barcode> getListBarcode {

get
{
if (_listofbarcode == null)
{
_listofbarcode = new List<Barcode>();
}
else
{
if (Session["barcodelist"] !=null)
{
_listofbarcode = (List<Barcode>)Session["barcodelist"];
}

}

return _listofbarcode;
}

set {
if (_listofbarcode==null)
{
_listofbarcode = new List<Barcode>();
}
_listofbarcode = value;

}

}

Answer Source

You're always set getListBarcode=new List();

You can refer my code below:

private List<Barcode> GetListBarCode()
{
   List<Barcode> getListBarcode = new List<Barcode>();
   if(Session["barcodelist"] != null)
   getListBarcode = (List<Barcode>) Session["barcodelist"];
   return getListBarcode;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download