繁体   English   中英

ViewBag.Message 未显示 ASP.NET MVC c#

[英]ViewBag.Message not showing ASP.NET MVC c#

我有一个名为 Index.cshtml 和 controller 名为 HomeController 的视图,我似乎无法向视图显示 ViewBag.Message 和 ViewBag.FileUrl。 代码正在运行,当文件成功上传时,我只是无法显示 ViewBag.message。

下面是我的代码

索引.cshtml

@{ 
ViewBag.Title = "Upload a file to S3 Bucket";
}

<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<h3>@ViewBag.FileUrl</h3>

<p>Use this area to browse image and upload to S3 bucket.</p>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
    @Html.TextBox("file", "", new { type = "file" }) <br />
    <input type="submit" value="Upload" />
    @ViewBag.FileUrl
    @ViewBag.Message
</div>
}    

家庭控制器.cs

[HttpGet]
public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion);
    var result = "";
    var keyName = file.FileName;
    var fileTransferUtility = new TransferUtility(s3Client);

    try
    {
        if (file.ContentLength > 0)
        {
            var filePath = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(file.FileName));
            var fileTransferUtilityRequest = new TransferUtilityUploadRequest
            {
                BucketName = bucketName,
                FilePath = filePath,
                StorageClass = S3StorageClass.StandardInfrequentAccess,
                PartSize = 6291456, // 6 MB.  
                Key = keyName,
                CannedACL = S3CannedACL.PublicRead
            };

            fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
            fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
            fileTransferUtility.Upload(fileTransferUtilityRequest);
            fileTransferUtility.Dispose();
        }
        result = string.Format("http://{0}.s3.amazonaws.com/{1}", bucketName, keyName);

        ViewBag.FileUrl = result;
        ViewBag.Message = "File Uploaded Successfully!!";
    }
    catch (AmazonS3Exception amazonS3Exception)
    {
        ViewBag.Message = "Error occurred: " + amazonS3Exception.Message;
    }

    return RedirectToAction("Index");
}

您分配ViewBag值,这些值会被后续的RedirectToAction()丢失。

这里找到了答案, 详细比较了 ViewData、ViewBag 和 TempData 在您的情况下, TempData应该可以工作。

您正在重定向结果,以便值变为 null,而不是在分配值的地方使用Tempdata并在重定向的地方获取它,

catch (AmazonS3Exception amazonS3Exception)
{
    Tempdata["Message"]="Error occurred: " + amazonS3Exception.Message;
}

Index操作方法,尝试如下,

[HttpGet]
public ActionResult Index()
{
    ViewBag.Message= (string)Tempdata["Message"]
    return View();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM