【问题标题】:Html.BeginForm wont call post methodHtml.BeginForm 不会调用 post 方法
【发布时间】:2014-11-14 03:33:03
【问题描述】:

我尝试将图像插入服务器,鉴于我使用 mvc2,我的代码是:

<% using (Html.BeginForm("Upload", "Main", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%><br />
   <input type="file" name="files" id="file1" size="25" />
   <input type="submit" value="Upload file" />      
<% } %>  

在 MainController 我使用:

[HttpPost]
    public ActionResult Upload()
    {
        foreach (string inputTagName in Request.Files)
        {
            HttpPostedFileBase file = Request.Files[inputTagName];
            if (file.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("../Images")
                        , Path.GetFileName(file.FileName));
                file.SaveAs(filePath);
            }
        }
     }

但是当我继续 submit 按钮时,我尝试调试并看到 public ActionResult Upload 没有调用。 有什么问题?

感谢

【问题讨论】:

  • “什么都没有发生”是对行为的非常模糊的描述。如果浏览器根本没有发布表单,那么这与您的服务器端代码无关。生成的客户端 HTML 是什么?是否有任何 JavaScript 拦截表单发布? JavaScript 控制台中是否有任何错误?是否有任何请求发送到服务器?该请求的响应是什么?您可以在这里进行很多的调试。
  • 我真的不明白,如果您在 VS 中编写代码,它会给您一个错误,即您的方法没有返回值,您需要 stackoverflow 吗?还是您没有粘贴所有方法?
  • 我试过这段代码并且运行良好,但是你的代码有一个错误你是错误的路径你选择你使用 HttpContext.Server.MapPath("../Images") 它应该是 HttpContext .Server.MapPath("~/Images/")

标签: c# asp.net asp.net-mvc razor asp.net-mvc-2


【解决方案1】:

您的代码无法编译,您需要在操作中返回一个ActionResult,即

    [HttpPost]
    public ActionResult Upload()
    {
        foreach (string inputTagName in Request.Files)
        {
            HttpPostedFileBase file = Request.Files[inputTagName];
            if (file.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("../Images")
                        , Path.GetFileName(file.FileName));
                file.SaveAs(filePath);
            }
        }
        // Below line is missing
        return View();
     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-24
    • 2012-10-28
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 2012-09-13
    相关资源
    最近更新 更多