Dou*_*ain 23 c# asp.net-mvc editorfor asp.net-mvc-2
鉴于此模型,是否可以使用Html.EditorFor()将文件上传输入元素呈现给页面?我玩了属性FileName的数据类型,它肯定会影响渲染的编辑器表单.
public class DR405Model
{
[DataType(DataType.Text)]
public String TaxPayerId { get; set; }
[DataType(DataType.Text)]
public String ReturnYear { get; set; }
public String FileName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
强类型*.aspx页面看起来像这样
<div class="editor-field">
<%: Html.EditorFor(model => model.FileName) %>
<%: Html.ValidationMessageFor(model => model.FileName) %>
</div>
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 38
使用HttpPostedFileBase在视图模型上表示上传文件更有意义,而不是string:
public class DR405Model
{
[DataType(DataType.Text)]
public string TaxPayerId { get; set; }
[DataType(DataType.Text)]
public string ReturnYear { get; set; }
public HttpPostedFileBase File { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后你可以有以下视图:
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
... input fields for other view model properties
<div class="editor-field">
<%= Html.EditorFor(model => model.File) %>
<%= Html.ValidationMessageFor(model => model.File) %>
</div>
<input type="submit" value="OK" />
<% } %>
Run Code Online (Sandbox Code Playgroud)
最后在里面定义相应的编辑器模板~/Views/Shared/EditorTemplates/HttpPostedFileBase.ascx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<input type="file" name="<%: ViewData.TemplateInfo.GetFullHtmlFieldName("") %>" id="<%: ViewData.TemplateInfo.GetFullHtmlFieldId("") %>" />
Run Code Online (Sandbox Code Playgroud)
现在控制器可能如下所示:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new DR405Model());
}
[HttpPost]
public ActionResult Index(DR405Model model)
{
if (model.File != null && model.File.ContentLength > 0)
{
var fileName = Path.GetFileName(model.File.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
model.File.SaveAs(path);
}
return RedirectToAction("Index");
}
}
Run Code Online (Sandbox Code Playgroud)
Pau*_*her 10
这是MVC 5的一个示例(htmlAttributes需要).
在〜\ Views\Shared\EditorTemplates下创建一个名为HttpPostedFileBase.cshtml的文件
@model HttpPostedFileBase
@{
var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
htmlAttributes["type"] = "file";
}
@Html.TextBoxFor(model => model, htmlAttributes)
Run Code Online (Sandbox Code Playgroud)
这将生成具有正确id和名称的控件,并在从模型EditorFor模板编辑集合时起作用.
添加:htmlAttributes = new {type =“ file”}
<div class="editor-field">
<%: Html.EditorFor(model => model.FileName, new { htmlAttributes = new { type = "file" }) %>
<%: Html.ValidationMessageFor(model => model.FileName) %>
</div>
Run Code Online (Sandbox Code Playgroud)
注意:我使用的是MVC 5,尚未在其他版本上进行测试。
| 归档时间: |
|
| 查看次数: |
17578 次 |
| 最近记录: |