簡體   English   中英

在MVC 4 Razor中使用Javascript添加會話

[英]Add Session using Javascript in MVC 4 Razor

我正在編寫上傳文件的應用程序,首先我需要對文件存儲進行一些配置,我閱讀了前十行並將其顯示給用戶,用戶提供了配置,然后我將上傳文件。

我嘗試了這個

<script>
document.getElementById('file').addEventListener('change', readSingleFile, false);
function readSingleFile(evt) {
    var FileBlock = "";   
    var contents="";
    var f = evt.target.files[0];
    if (f) {
        var r = new FileReader();
        r.onload = function (e) {
            contents = e.target.result;
            var Rows = contents.toString().split("\n", 10);
            FileBlock = Rows[0];
             for (var i = 1 ; i < Rows.length; i++) {
                 FileBlock += "|" + Rows[i];
             }
             alert(contents);

            @{
                Session["Test"] = @:contents+"";
             }

            OpenDockPanelBySumbitForm("ImporterPanel", "form",FileBlock);
            Hide_ContentZone_Panel();
        }
        r.readAsText(f);      
    } else {
        alert("Failed to load file");
    }
}

這段代碼不起作用

@{
   Session["Test"] = @:contents+"";
 }

如果有人可以幫助我將不勝感激,謝謝您的參與。

我發現沒有辦法做到這一點,因為C#代碼首先在Javascript之前編譯,所以C#將無法看到Javascript代碼,而可能相反。

一種解決方法是將腳本移動到另一個文件夾-plugins-以確保它首先被編譯。

在此處檢查源

Asp.net代碼正在Javascript中運行基於服務器的動態工作。 JavaScript無法根據服務器為變量分配值。 但是,保留隱藏變量可以使用;

http://i.hizliresim.com/aq336d.png

<input type="hidden" id="hdnsession" name="sessionData" value=" @ViewBag.session??"" " />
public ActionResult test(string sessionData){
Session["Test"] = sessionData;
ViewBag.session = Session["Test"];
return View();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM