gpt4 book ai didi

c# - MVC-4 在服务器端更改 ViewBag.Message?

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:08 25 4
gpt4 key购买 nike

我是 MVC 编码的初学者。
当应用程序启动时,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
}

我的 Controller :

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();
}
}
}

最佳答案

简短的回答是。我猜是因为你是“新手”,所以你想专注于 MVC 部分,但 MVC 和 JavaScript 是非常相互关联的,想想客户端 (JavaScript) 和服务器 (MVC),你应该真正掌握两者才能制作出好的网站。

通常服务器不会向浏览器发送事件,而是由浏览器发出请求。有一些方法可以让服务器使用诸如 SignalR 之类的东西在客户端上引发事件但在这种情况下,这就太过分了。

最后...您要实现的很大程度上是客户端操作,即通知用户做某事。如果您在 MVC 中这样做,您会浪费网络带宽并增加延迟(认为服务器调用很昂贵),而实际上它是一个客户端操作,因此应该在 JavaScript 中完成。

不要回避 JavaScript。拥抱它。查看JQuery这为您减轻了很多繁重的工作。

关于c# - MVC-4 在服务器端更改 ViewBag.Message?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16561215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com