![](/img/trans.png)
[英]How do I use Webforms and ASP.NET MVC together in an ASP.NET Webforms Website project?
[英]How do I get files AND form values from an ASP.NET MVC 4 website?
我有一個ASP.NET MVC網站,其中有一個下拉列表,正在視圖中使用它創建...
@Html.DropDownList("Programs")
程序從Business Object集合填充,並填充到Home Controller上的索引操作中的ViewBag中......
\\get items...
ViewBag.Programs = items;
該視圖還有三個我在同一視圖中得到的文件...
<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" />
所有上述控件都包含在使用...在視圖中創建的表單中
@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" />
}
我的問題是我找不到處理所有文件的方法並引用表單字段。
具體來說,我需要知道用戶從下拉菜單中選擇的程序。
我可以使用這段代碼處理文件沒有問題...
[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");
}
但我無法弄清楚如何獲取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
}
那個using語句應該將表單值和文件作為ActionResult的單獨參數來獲取?
編輯我的編輯
似乎我不必進行任何更改......調試器顯示文件和表單都是非空的。 涼! 是對的嗎?
我認為應該這樣做
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files, FormCollection form)
{
//handle the files
//handle the returned form values in the form collection
}
您應該能夠在[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
使用同時包含張貼的文件和形式值的視圖模型的類型,或使用HttpRequest
(通過訪問Controller.Request
對象,它具有性質) .Form[key]
為POST值和.Files[key]
張貼的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.