这是我的模特。
public class Libro
{
[Key]
[ScaffoldColumn(false)]
public int ID { get; set; }
[Required]
[MaxLength(300, ErrorMessage = "El Path debe tener como máximo 300 caractéres")]
[Display(Name = "Ruta de acceso")]
public string Path { get; set; }
[Required]
[MaxLength(80, ErrorMessage = "El nombre debe tener como máximo 80 caractéres")]
public string Nombre { get; set; }
[Required]
[Display(Name = "Ruta de acceso")]
public HttpPostedFileBase File { get; set; }
//Relations
public virtual ICollection<Hoja> Hojas { get; set; }
}
以下是我的观点:
@model xx.Models.Libro
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Libro</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(x => x.File, new { type = "file" })
@*@Html.EditorFor(model => model.File, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.File, "", new { @class = "text-danger" })*@
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Nombre, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Nombre, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Nombre, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Nombre")] Libro libro)
{
if (ModelState.IsValid)
{
foreach (string upload in Request.Files)
{
if (Request.Files[upload].ContentLength == 0) continue;
string pathToSave = Server.MapPath("~/App_Data/Uploads");
string filename = Path.GetFileName(Request.Files[upload].FileName);
Request.Files[upload].SaveAs(Path.Combine(pathToSave, filename));
libro.Path = Path.Combine(pathToSave, filename);
db.Libro.Add(libro);
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(libro);
}
答案 0 :(得分:8)
您需要将表单上的encType
设置为multipart/form-data
;
@using (Html.BeginForm("Create", "ControllerName", FormMethod.Post,
new { encType="multipart/form-data" }))
该文件也可在您的模型中使用,即libro.File
。
答案 1 :(得分:3)
尝试将BeginForm
更改为:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post,
new { enctype = "multipart/form-data" }))