我正在尝试将文件上传到目录。以下代码对我有用
控制器
[HttpPost]
public ActionResult Index(HttpPostedFileBase uploadFile)
{
//string path = @"C:\Users\thomas\Desktop";
if (uploadFile != null)
{
string filePath = Path.Combine(Server.MapPath("/files"), Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return RedirectToAction("Index");
}
网页
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="/Post/Index" method="post" enctype="multipart/form-data">
<label for="uploadFile">Upload file: </label>
<input name="uploadFile" id="uploadFile" type="file" />
<input value="uploadFile" type="submit" />
</form>
现在我试图在一个函数中实现这一点,在该函数中我创建一个消息,该消息由包含消息和项目类的模型创建。当我提交表单时,模型将传递给我的保存控制器,但我的参数控制器中的文件为空。
网页
创建新消息
@model GeoCitytroopers.Models.MessageItemModel
@{
ViewBag.Title = "Create";
}
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Event</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Message.MessagePicture)
</div>
<div>
<label for="uploadFile">Upload file: </label>
<input name="uploadFile" id="uploadFile" type="file" />
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Message.MessagePicture)
@Html.ValidationMessageFor(model => model.Message.MessagePicture)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Item.ItemTitle)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Item.ItemTitle)
@Html.ValidationMessageFor(model => model.Item.ItemTitle)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Item.ItemDescription)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Item.ItemDescription)
@Html.ValidationMessageFor(model => model.Item.ItemDescription)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
控制器
[HttpPost]
public ActionResult Create(HttpPostedFileBase uploadFile, MessageItemModel ViewModel)
{
if (ModelState.IsValid)
{
Utility ut = new Utility();
Item viewItem = ViewModel.Item;
Message viewMessage = ViewModel.Message;
if (uploadFile != null)
{
string filePath = Path.Combine(Server.MapPath("/files"), Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
//ADD USER TO ITEM
viewItem = ut.AddUserToItem(viewItem);
//ADD ITEM
viewItem.ItemCreateddate = DateTime.Now;
//ADD DISTRICT TO ITEM
viewItem.DistrictID = ut.GetUserDistrict();
db.Items.Add(viewItem);
//ADD LINK
viewMessage.Item = viewItem;
db.Messages.Add(viewMessage);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(ViewModel);
}
如何将上传文件传递给我的控制器?提前致谢!