C# 是否可以使用EditorFor()创建<;输入类型=";文件">;?
给定此模型,是否可以使用Html.EditorFor()将文件上载输入元素呈现到页面?我处理了属性文件名的数据类型,这肯定会影响呈现的编辑器表单C# 是否可以使用EditorFor()创建<;输入类型=";文件">;?,c#,asp.net-mvc,asp.net-mvc-2,editorfor,C#,Asp.net Mvc,Asp.net Mvc 2,Editorfor,给定此模型,是否可以使用Html.EditorFor()将文件上载输入元素呈现到页面?我处理了属性文件名的数据类型,这肯定会影响呈现的编辑器表单 public class DR405Model { [DataType(DataType.Text)] public String TaxPayerId { get; set; } [DataType(DataType.Text)] public String ReturnYear { get; set; }
public class DR405Model
{
[DataType(DataType.Text)]
public String TaxPayerId { get; set; }
[DataType(DataType.Text)]
public String ReturnYear { get; set; }
public String FileName { get; set; }
}
强类型*.aspx页面如下所示
<div class="editor-field">
<%: Html.EditorFor(model => model.FileName) %>
<%: Html.ValidationMessageFor(model => model.FileName) %>
</div>
model.FileName)%%>
model.FileName)%%>
否,但请看一看在视图模型上表示上载的文件比使用字符串
更有意义:
public class DR405Model
{
[DataType(DataType.Text)]
public string TaxPayerId { get; set; }
[DataType(DataType.Text)]
public string ReturnYear { get; set; }
public HttpPostedFileBase File { get; set; }
}
然后您可以看到以下视图:
<% 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" />
<% } %>
现在控制器可能如下所示:
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");
}
}
这里有一个MVC5的例子(htmlAttributes需要) 在~\Views\Shared\EditorTemplates下创建一个名为HttpPostedFileBase.cshtml的文件
@model HttpPostedFileBase
@{
var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
htmlAttributes["type"] = "file";
}
@Html.TextBoxFor(model => model, htmlAttributes)
这将生成具有正确id和名称的控件,并在从model Editor for template编辑集合时起作用。添加:
htmlAttributes=new{type=“file”}
model.FileName,新的{htmlAttributes=new{type=“file”})%>
model.FileName)%%>
注意:我使用的是MVC 5,我还没有在其他版本上进行测试。已经构建了它。也许我走错方向了。我有aspnet_db配置文件数据,需要与上传的文件结合。因此,用户文件以
user\u id
+date
+“xlsx”
保存到服务器上,我想我需要创建一个模型,它的属性不仅仅是file对象。谢谢,这就是我要寻找的答案。你也可以使用@Html.TextBoxFor(x=>x.file,new{type=“file”})
@Darin-如果我将文件url保存到数据库中,数据类型是什么。在您使用的“HttpPostedFileBase”MVC4模型中,我一直在想为什么DataType.Upload不呈现type=“file”这里需要注意的是,幕后可能会发生更多的事情。在.cshtml文件属性中的设置被切换之前,上述操作将无法工作:构建操作,无-->内容。根据对这个问题的回答:几点,默认情况下,.cshtnl的构建操作是内容的,您所指的答案是从2011年开始的,并且谈论MVC 3-MVC 5,我必须不做任何更改才能使这个工作像breeze一样工作。除编辑器模板外,无需额外更改
@model HttpPostedFileBase
@{
var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
htmlAttributes["type"] = "file";
}
@Html.TextBoxFor(model => model, htmlAttributes)