1

私はMVCコーディングの初心者です。
アプリケーションが起動すると、ViewBag.Message は次のようになります。 アップロードするファイルを選択してください。

アップロードが成功すると、次のように変わります。

javascriptを使用せずに、約5秒後に「アップロードするファイルを選択してください」というメッセージに戻って表示する方法はありますか? 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();
        }
    }
}
4

1 に答える 1

7

短い答えはいいえです。あなたは「新しい」ので、MVC の部分に集中したいのですが、MVC と JavaScript は非常に相互に関連していると思います。クライアント (JavaScript) とサーバー (MVC) を考えてください。

通常、サーバーはブラウザに対してイベントを発生させず、代わりにブラウザがリクエストを行います。SignalRなどを使用してサーバーにクライアントでイベントを発生させる方法はありますが、このシナリオではやり過ぎです。

最後に...あなたが達成しようとしているのは、非常にクライアント側のアクションです。つまり、ユーザーに何かをするように通知します。MVC でそれを行うと、ネットワーク帯域幅を浪費し、遅延を追加することになります (サーバー呼び出しはコストがかかると考えてください)。実際にはそれがクライアント アクションであるため、JavaScript で行う必要があります。

JavaScript をためらわないでください。抱きしめて。多くの面倒な作業を取り除いてくれるJQueryを調べてください。

于 2013-05-15T09:28:57.927 に答える