1

我需要上传一个文件,我找到了几种方法。我认为最好的方法是根据这个博客: 博客

我还在这里找到了一个有用的帖子: stackoverflow topic

但是当我尝试它时,它失败了。我在 Visual Studio 中收到以下错误:

序列包含一个以上的元素,没有更多可以继续下去了。

我的代码如下所示:

控制器:

public PartialViewResult Index(parameterlist)
    {
        var model = new Model();


        return PartialView(model);
    }

[HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        // Verify that the user selected a file
        if (file != null && file.ContentLength > 0) 
        {
            // extract only the filename
            var fileName = Path.GetFileName(file.FileName);

            var path =         Path.Combine(Server.MapPath(@"Path"), fileName);
            file.SaveAs(path);
        }
        // redirect back to the index action to show the form once again
        return RedirectToAction("Index");            
    }

看法:

            <div class="span6">                                
            @using (Html.BeginForm("null", "null", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                <input type="file" name="file" />
                <input type="submit" value="OK" />
            }
        </div>

所以当这个部分视图被调用时,它会转到 actionResult 方法,当然没有选择文件,因为视图还没有打开。视图中还有其他一些文本框和下拉菜单。但没什么特别的,有人知道我做错了什么吗?我有一种感觉,我错过了一些重要的东西......

4

2 回答 2

1

为避免执行错误的函数,您应该在 Html.BeginForm 中指定 Controller 和 Action 而不是那里的空值。

@using (Html.BeginForm("Index", "YourController", FormMethod.Post, ...
于 2012-10-05T12:09:44.777 回答
0

我尝试将它们合并到一个表单中,所以我的表单现在看起来像这样:

@using (Ajax.BeginForm("Method", "Controller",new { enctype = "multipart/form-data" }, new AjaxOptions { HttpMethod = "Post", OnSuccess = "Method" }, new { @class = "css", id = "formname" }))
{
   Some divs and stuff

   <input type="file" name="file" class="btn btn-inverse" />
   </div>

该函数如下所示:

[HttpPost]
        public void _SaveDocument(Model model, HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath(@"Path"), fileName);
                file.SaveAs(path);

                var command = new command()
                {
                    Model = model
                };
                commandDispatcher.Dispatch(command);
            }            
        }

但是文件永远不会被添加,它总是空的

于 2012-10-05T13:24:04.253 回答