2013-05-15 56 views
1

我是MVC編碼的初學者。
當應用程序啓動時,ViewBag.Message是:選擇一個要上傳的文件。MVC-4在服務器端更改ViewBag.Message?

成功上傳後,它變爲:文件上傳成功!

有沒有一種方法可以讓我們在5秒後再次返回並顯示「選擇要上傳的文件」消息,而無需使用任何JavaScript? 我以爲如果MVC有一些內置的時間功能,我可以使用也許?

https://github.com/xoxotw/mvc_fileUploader

我的觀點:

@{ 
    ViewBag.Title = "FileUpload"; 
} 

<h2>FileUpload</h2> 

<h3>Upload a File:</h3> 


    @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new {enctype = "multipart/form-data"})) 
    { 
     @Html.ValidationSummary(); 
     <input type="file" name="fileToUpload" /><br /> 
     <input type="submit" name="Submit" value="upload" /> 
     @ViewBag.Message 
    } 

我的控制器:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace Mvc_fileUploader.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      ViewBag.Message = "Choose a file to upload!"; 
      return View("FileUpload"); 
     } 

     [HttpPost] 
     public ActionResult FileUpload(HttpPostedFileBase fileToUpload) 
     { 

      if (ModelState.IsValid) 
      { 
       if (fileToUpload != null && fileToUpload.ContentLength > (1024 * 1024 * 1)) // 1MB limit 
       { 
        ModelState.AddModelError("fileToUpload", "Your file is to large. Maximum size allowed is 1MB !"); 
       } 

       else 
       { 
        string fileName = Path.GetFileName(fileToUpload.FileName); 
        string directory = Server.MapPath("~/fileUploads/"); 

        if (!Directory.Exists(directory)) 
        { 
         Directory.CreateDirectory(directory); 
        } 

        string path = Path.Combine(directory, fileName); 
        fileToUpload.SaveAs(path); 

        ModelState.Clear(); 
        ViewBag.Message = "File uploaded successfully!"; 
       } 
      } 

       return View("FileUpload"); 

     } 



     public ActionResult About() 
     { 
      ViewBag.Message = "Your app description page."; 

      return View(); 
     } 

     public ActionResult Contact() 
     { 
      ViewBag.Message = "Your contact page."; 

      return View(); 
     } 
    } 
} 
+0

你必須使用javascript做到這一點。你爲什麼要尋找一個非JavaScript的解決方案? – nemesv

回答

7

簡短的回答是沒有。我猜測,因爲你是「新」,你想專注於MVC部分,但MVC和JavaScript非常相互關聯,認爲客戶端(JavaScript)和服務器(MVC),你應該真的掌握這兩個,以建立良好的網站。

通常情況下,服務器不會向瀏覽器觸發事件​​,而是瀏覽器發出請求。有辦法讓服務器在客戶端上使用諸如SignalR之類的事件來引發事件,但在這種情況下這可能是矯枉過正的。

最後...你試圖實現的是非常多的客戶端行爲,即通知用戶做某事。如果你是在MVC中做的話,那麼當真的是一個客戶端操作時,你會浪費網絡帶寬並增加延遲(認爲服務器調用很貴),所以應該用JavaScript來完成。

不要回避JavaScript。擁抱它。看看JQuery,這需要很多繁重的工作。

+0

謝謝,非常好的答案,我現在知道該看什麼。^_^ –

+0

歡迎您@xoxo_tw快樂學習!你會發現** StackOverflow **一個寶貴的資源,我有/做! – Belogix