2012-05-16 89 views
0

我需要一个动作来创建MyModel类型的一些字段,还有一些文件要上传到数据库。所以这是我的视图的一部分:上传文件在MVC 3

@using(Html.BeginForm()) { 

<fieldset> 
<dl> 
    <dt> 
    @Html.LabelFor(model => model.Name) 
</dt> 
<dd> 
    @Html.EditorFor(model => model.Name) 
    @Html.ValidationMessageFor(model => model.Name) 
</dd> 
    <dt> 
@Html.LabelFor(model => model.NeededFiles) 
</dt> 
    <dd> 
@foreach(var item in Model.NeededFiles) { 
<div style="margin:5px;"> 
     @Html.Label(item.Title) 
     <input type="file" name="@item.Name" /> 
</div> 
} 
    </dl> 
</fieldset> 
<input type="submit" value="Create" class="button red" /> 
} 

但在行动后,我有一些问题得到文件路径: 这是我的操作:

[HttpPost] 
public ActionResult Create(MyModel ViewModel FormCollection collection, IEnumerable<HttpPostedFileBase> files) { 

//.... 
} 

Request.Filesnull所以我不能使用它,我不知道为什么。还有文件IEnumerable<HttpPostedFileBase>为空。然后我试着从FormCollection 得到,所以我用这个:

string filePath = collection.GetValue(item.Name).AttemptedValue; 

filePath只是返回的文件名不是文件的路径,我不明白。当我选择文件时,我可以看到输入中的所有路径,但是当我想要得到它时,只需返回文件Name。我的问题在哪里?你的建议是什么?

回答

1

您应修改您的视图以包括多部分/格式数据:

@using(Html.BeginForm("YourAction", "YourController", FormMethod.Post, new { enctype = "multipart/form-data" })) { 
    //.... 
}