如何从ASP.NET MVC 4网站获取文件和表单值?

Set*_*man 9 c# forms asp.net-mvc http asp.net-mvc-4

我有一个ASP.NET MVC网站,它有一个下拉列表,在视图中使用它创建...

@Html.DropDownList("Programs")
Run Code Online (Sandbox Code Playgroud)

程序从Business Object集合填充,并填充到Home Controller上的索引操作中的ViewBag中......

\\get items...
ViewBag.Programs = items;
Run Code Online (Sandbox Code Playgroud)

该视图还有三个我在同一视图中得到的文件...

<input type="file" name="files" id="txtUploadPlayer" size="40" />  
<input type="file" name="files" id="txtUploadCoaches" size="40" />  
<input type="file" name="files" id="txtUploadVolunteers" size="40" /> 
Run Code Online (Sandbox Code Playgroud)

所有上述控件都包含在使用...在视图中创建的表单中

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
     <!--  file and other input types  -->
     <input type="submit" name="btnSubmit" value="Import Data" />
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我找不到处理所有文件的方法并引用表单字段.

具体来说,我需要知道用户从下拉菜单中选择的程序.

我可以使用这段代码处理文件没有问题...

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
//public ActionResult Index(FormCollection form)
{

    _tmpFilePath = Server.MapPath("~/App_Data/uploads");

    if (files == null) return RedirectToAction("Index");
    foreach (var file in files)
    {
        if (file != null && file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(_tmpFilePath, fileName);
            if (System.IO.File.Exists(path)) System.IO.File.Delete(path);

            _file = file;

            file.SaveAs(path);

            break;  //just use the first file that was not null.
        }
    }



    //SelectedProgramId = 0;

    //DoImport();

    return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何获取POST表单值,尤其是"程序"下拉列表选择值(对于记录,还有一个复选框,我无法从中读取值.)Fiddler向我显示响应具有文件引用AND选定的程序,但我无法弄清楚如何使用ASP.NET MVC将它们从POST中取出.

我知道这个问题非常基本,但我还在学习整个web/http的东西,而不仅仅是MVC.

编辑 感谢您的回答.我认为答案可能在于将文件和表单值都传递到POST中.

所以我的最后一个问题是......如何更改HTML.BeginForm块以传递文件和表单值?现在我有......

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  //do stuff
}
Run Code Online (Sandbox Code Playgroud)

那个using语句应该将表单值和文件作为ActionResult的单独参数来获取?

编辑我的编辑
似乎我不必进行任何更改...调试器显示文件和表单都是非空的.凉!是对的吗?

Amm*_*mar 8

我认为应该这样做

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files, FormCollection form)
{
  //handle the files

  //handle the returned form values in the form collection
}
Run Code Online (Sandbox Code Playgroud)

您应该能够在[HttpPost]操作中传入2个参数.您也可以传入HTML名称.

编辑:我在ASP.net中也遇到了表单问题.我建议看一下Scott Allen撰写的这篇博文. http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx