如何在ASP.net MVC 3中成功上载文件后显示警报

时间:2013-01-07 10:37:06

标签: javascript asp.net-mvc-3 file-upload jsonresult

现在我能够成功上传文件...我现在正在尝试做的是如果文件成功上传则显示警告框,或者如果没有显示错误/异常警告...

以下是我的观点:

using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data"}))
        {
        <div class="control-group">                
            <input type="file" id="file" name="file" />
            <input type="submit" value="Upload" />
        </div>
        }

这是我的控制器:

[HttpPost]   
public ActionResult Upload(HttpPostedFileBase file)
{
    try
    {
        //some code here for the upload....             

        /*In this part is my problem...Both Lines below is not showing the alert...*/
        //return new JavaScriptResult() { Script = "alert('The calendar XML file was uploaded successfully!');" };
        //return JavaScript("alert('The calendar XML file was uploaded successfully!');");
    }

    catch (Exception e)
    {   
        log.Error("HomeController::Upload()", e);
        return new JavaScriptResult() { Script = "alert(\"" + e.Message + "\");" };
    }
}

我想要的是我的观点仍然存在......没有重定向页面...只是显示该消息的警告框...谢谢!非常感谢任何想法,因为我知道这种方式不推荐......:)

2 个答案:

答案 0 :(得分:1)

这就是我从控制器获取警报所做的工作

以下是查看代码:

@using (@Html.BeginForm("DoSomething","secure"))
{
    <input type="submit" value="get alert" />
}

这是控制器代码:

[HttpPost]
        public ActionResult DoSomething()
        {
            string message = "hai";
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<script type = 'text/javascript'>");
            sb.Append("window.onload=function(){");
            sb.Append("alert('");
            sb.Append(message);
            sb.Append("')};");
            sb.Append("</script>");
            //return Content("<script type='text/javascript'>alert('Hello there');</script>"); //You can get the alert with this line also
            return Content(sb.ToString(), "text/javascript");
        }

即使不需要脚本,也会在点击get alert按钮时直接显示警告

希望有所帮助

答案 1 :(得分:1)

我能找到合适的解决方案here.

上面的链接用于在提交表单之前显示一个确认框,并显示我的控制器返回的json对象消息的警告...

return Json(new { isok = true, message = "Successfully uploaded the calendar XML file!" }, "application/octet-stream");