我使用ASP.NET MVC和下面的ASP.NET网站上的教程中的说明“工具入门与 - 使用MVC的EF-”。 我有一个设备类
public class Equipment
{
[Key] public int EquipID { get; set; }
public string EquipName { get; set; }
public string EquipDescription { get; set; }
public string EquipSerialNumber { get; set; }
public string EquipImage { get; set; }
public string EquipManufacturor { get; set; }
public string EquipLocation { get; set; }
public string EquipCalibrationFreq { get; set; }
public virtual ICollection<Calibration> Calibrations { get; set; }
}
我的任务是,当用户添加新的设备,然后点击创建窗体上应该有一个FileUpload控件,它允许选择一个文件,当保存记录这个文件应该在文件夹中复制其路径将被存储在字段“ EquipImage。
这里是观的CSHTML
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Equipment</legend>
<div class="editor-label">
@Html.LabelFor(model => model.EquipName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EquipName)
@Html.ValidationMessageFor(model => model.EquipName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.EquipDescription)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EquipDescription)
@Html.ValidationMessageFor(model => model.EquipDescription)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.EquipSerialNumber)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EquipSerialNumber)
@Html.ValidationMessageFor(model => model.EquipSerialNumber)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.EquipImage)
</div>
<input type="file" name="file"/>
<div class="editor-label">
@Html.LabelFor(model => model.EquipManufacturor)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EquipManufacturor)
@Html.ValidationMessageFor(model => model.EquipManufacturor)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.EquipLocation)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EquipLocation)
@Html.ValidationMessageFor(model => model.EquipLocation)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.EquipCalibrationFreq)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EquipCalibrationFreq)
@Html.ValidationMessageFor(model => model.EquipCalibrationFreq)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
和最后但并非最不重要的设备控制器
public ActionResult Create()
{
return View();
}
//
// POST: /Equipment/Create
// This action handles the form POST and the upload
[HttpPost]
public ActionResult Create(HttpPostedFileBase file, Equipment equipment)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/Content/EquipImages"), fileName);
file.SaveAs(path);
}
if (ModelState.IsValid)
{
db.Equipments.Add(equipment);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(equipment);
}