Man*_*kar 17 asp.net-mvc asp.net-mvc-scaffolding
我想在我的表单上提供一个工具,供用户上传文件并保存在数据库中.如何在ASP.NET MVC中完成.
在我的模型类中写入什么DataType.我试过Byte[],但在脚手架中,解决方案无法在相应的视图中为它生成适当的HTML.
这些案件是如何处理的?
Dar*_*rov 43
您可以byte[]在模型上使用a ,HttpPostedFileBase在视图模型上使用a .例如:
public class MyViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
byte[] uploadedFile = new byte[model.File.InputStream.Length];
model.File.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
// now you could pass the byte array to your model and store wherever
// you intended to store it
return Content("Thanks for uploading the file");
}
}
Run Code Online (Sandbox Code Playgroud)
最后在你看来:
@model MyViewModel
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
@Html.LabelFor(x => x.File)
@Html.TextBoxFor(x => x.File, new { type = "file" })
@Html.ValidationMessageFor(x => x.File)
</div>
<button type="submit">Upload</button>
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40994 次 |
| 最近记录: |