Html.BeginForm不会调用post方法

时间:2014-09-19 13:52:43

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

我尝试将图像插入服务器,在视图中我使用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没有调用。 可能有什么问题?

感谢名单

1 个答案:

答案 0 :(得分:3)

您的代码无法编译,您需要在操作中返回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();
     }