ASP.NET MVC3 - TempData的Session消失問題

網友一篇「 MVC 3上,Session消失的問題與解決辦法」引起我的興趣,我留言要了些基本的Code,以下是我驗證程式碼,結論是,Session並不會消失,怪怪!

Step 1. 新增Controller及Action
以下程式碼為驗證使用,沒有進行任何安全過濾,請不要使用。

Imports System.IO 

Namespace UpDownFileFromDBMvc
    Public Class FileUploadAndSessionTestController
        Inherits System.Web.Mvc.Controller

        '
        ' GET: /FileUploadAndSessionTest/Upload

        Function Upload()
            Return View()
        End Function

        
        Function Upload(upfile As HttpPostedFileBase )
            If upfile  IsNot Nothing andalso upfile.ContentLength > 0 Then
                Dim savePath As String = Path.Combine(Server.MapPath("~/Files/"), upfile.FileName)
                upfile.SaveAs(savePath)
                TempData("FileName") = upfile.FileName 
            End If

            Return RedirectToAction("FileInfo")
        End Function

        Function FileInfo()
            ViewBag.FileName = TempData("FileName")
            Return View()
        End Function

    End Class
End Namespace

以上參考該網友提供程式碼,我所撰寫的VB程式碼。

Step 2. 新增Upload與FileInfo的View

Upload.aspx

<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Upload
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Upload</h2>
<%Using Html.BeginForm("Upload", "FileUploadAndSessionTest", FormMethod.Post, New With {.enctype = "multipart/form-data"})%>
    <%: Html.ValidationSummary(True)%>
    File:<input id="upfile" name="upfile" type="file" value="" />
    <br />
    <input type="submit" value="Upload" />
<%End Using%>
</asp:Content>

FileInfo.aspx

<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
FileInfo
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>FileInfo</h2>
Upload File Nale: <%: ViewBag.FileName %>
</asp:Content>

以下為執行結果圖。

Upload File then Pass file name
圖一:Upload File then Pass file name(點擊看大圖)
程式唯一不同處只有路徑我有先使用Path.Combine處理過,不知道是不是這個原因。

沒有留言:

張貼留言

感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。