2017-12-04 59 views
0

私はいくつかのbelowsを持っています、どのように私はコントローラからJavascriptコードでセッションを取得することができます助けてください?ASP.NET MVCからjavascriptでセッションを取得する方法

public ActionResult Login(FormCollection f) 
    { 
     string sAcount = f["txtAccount"].ToString(); 
     string sPassword = f.Get("txtPassword").ToString(); 

     tblCustom cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword); 

     if (cs != null) 
     { 

      Session["Account"] = cs; 

      return View(); 

     } 

     return View(); 

    } 

とJSコードは、結果がSTIL​​警告である私を助けて、動作していない

 <script > 

     $('#btnSendMsg').click(function() { 

        var msg = $("#txtMessage").val(); 

        alert('Hello' + Session["Account"]); 
       }); 

    <script/> 

です。

+0

あなたはセッションに 'tblCustoms'オブジェクトではなく、文字列を設定しています。セッションからそれを読んで、あなたのアラートのプロパティ値を使用してください。プレフィックス '@ 'を使用してC#コードブロックを開始することができます。 – Shyju

+0

実際、私はコントローラセッション["Account"] = "abc"を設定しました。 、JS alert( 'Hello' + @Session ["Account"])でも、私はまだ働いていません。 –

答えて

0

これはあなたの質問に直接答えるものではありませんが、好ましい方法は、パラメータを渡したり取得したりする際に、ViewModelsを作成することです。

LoginViewModelを作成します。代わりに、ビューへ

public class LoginViewModel { 
    public tblCustoms Customs { get; set; } 
    //other stuff you have, you might consider moving account and password here too, 
    //instead of capturing with textbox names 

    //public string Account { get; set; } 
    //public string Password { get; set } 
} 

パス。

public ActionResult Login(FormCollection f) 
{ 
    string sAcount = f["txtAccount"].ToString(); 
    string sPassword = f.Get("txtPassword").ToString(); 

    var cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword); 

    if (cs != null) 
    { 
     Session["Account"] = cs; 

     //return View(); you don't need this line 
    } 

    return View(new LoginViewModel() { Customs = cs }); 

} 

ビューの一番上に追加します。

@model YourNameSpace.LoginViewModel 

とJavaScriptで:これらのすべてに代わるものとして

<script> 
    $('#btnSendMsg').click(function() { 
     var msg = $("#txtMessage").val(); 
     alert('Hello ' + @Model.Customs); 
    }); 
<script/> 

を、あなたはViewBagを使用することができます。その後

ViewBag.Customs = cs; 

をビューでそれを呼び出す:コントローラメソッドで 、任意の名前に割り当て

alert('Hello ' + @ViewBag.Customs); 

あなたのビューでセッションを使用するためには、これを試してみてください。

@Session["Account"].ToString(); 
+0

グローバル変数へのセッションを全ページで使いたいと思います。 –

+0

アップデートを参照してください。 文字列にキャストします。 – Mithgroth

0

セッションを何度も更新しないでください。セッションに保存されるデータの種類は、ユーザーの役割、ページの権限およびその他のグローバル情報です。ログインが完了したら、login cookieを設定する必要があります。ログインの場合、FormsAuthentication Cookieを使用する必要があります。

フォーム認証Cookieを設定するには、set Forms authenticationに従います。 またはこのリンクを確認してくださいCreate Forms Authentication cookie

ページの使用では

alert("@HttpContext.Current.User.Identity.Name"); 
関連する問題