2017-02-28 8 views
-1

私はこのコードをリストに追加する前に重複をチェックしています。 しかし、毎回Ajaxのポストコールの後。リストは0に戻されます。MVCグローバルリストがajaxのポストバックの後にリセットされました

とにかくリストのデータを維持するには?

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

**コントローラー*:*

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

    } 

編集1 遅延ゲッターとセッター

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; 

     } 

} 

答えて

1
を使用した場合、コードの実行を割り当てることで

あなたは常に設定されていますgetListBarcode = new List();

private List<Barcode> GetListBarCode() 
{ 
    List<Barcode> getListBarcode = new List<Barcode>(); 
    if(Session["barcodelist"] != null) 
    getListBarcode = (List<Barcode>) Session["barcodelist"]; 
    return getListBarcode; 
} 
+0

あなたは私のために働く:

あなたは以下の私のコードを参照することができます。ちょうど私も以下のコードを試しましたが、割り当てに遅れがありました。 –

関連する問題