Una*_*avi 3 asp.net-mvc file-upload
我的控制器
public ActionResult Edit(int id)
{
return this.EditDefault(id);
}
[HttpPost]
public ActionResult Edit(int id, Models.Company model)
{
return this.EditDefault(id, model);
}
Run Code Online (Sandbox Code Playgroud)
我的模特
pulbic class Company
{
... Many other Propeties
public HttpPostedFileBase File { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的看法
@using (Html.BeginForm(new { enctype = "multipart/form-data" }))
{
... Many other Properties
@Html.TextBoxFor(m => m.File, new
{
type = "file", style = "display:none"
})
... Submit
}
Run Code Online (Sandbox Code Playgroud)
所以现在我的问题是,当我提交页面时,模型中的信息是正确的,但文件属性仍为空.
我找到了一些解决方案,人们在控制器中添加了HttpPostedFileBase作为参数(试过它也不起作用),但我想避免这种情况,因为模型和控制器是用T4生成的.那么有人知道为什么File Property总是为null吗?
一些帮助真的很高兴:)
更新:找到解决方案thx到Matt Tabor.
对我来说,解决方案看起来像这样,因为我使用共享的编辑页面.javascript部分是隐藏实际的文件上传元素并使用跨度,因为文件上传不是样式的.
//Shared Part
@{
RouteData routeData = this.ViewContext.RouteData;
string currentController = routeData.GetRequiredString("controller");
}
@using (Html.BeginForm("Edit", currentController, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
//Special Part
... Many other Properties
//File upload which is hidden
@Html.TextBoxFor(m => m.File, new
{
type = "file", style = "display:none"
})
//Span which forwards the clicks to the file upload
<span id="fake-file-name">Kein Bild</span>
... Submit
}
<script type="text/javascript">
$(function () {
//forward the click from the span to the file upload
$("#fake-file-name").click(function () {
$("#File").click();
});
//display the chosen file name to the user with the styled span
$("#File").bind('change', function () {
//we don't want the C:\fakepath to show
var displayFileName = this.value.replace("C:\\fakepath\\", "");
$("#fake-file-name").text(displayFileName);
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
您需要将表单方法指定为post
@using (Html.BeginForm("Edit", "CONTROLLER", null,FormMethod.Post, new { enctype = "multipart/form-data" }))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12517 次 |
| 最近记录: |