首先,我很抱歉我的英语不好。我是 ASP.NET MVC 的新手,目前我正在用它做小型“租车”项目。
我想制作一个表单,页面管理员可以在页面上添加汽车,其中包含详细信息,例如name
, year of production
and picture
。在学习了一些教程之后,我制作了一个表单来创建带有名称和生产年份的汽车,并且我单独制作了一个表单,管理员可以在其中上传汽车的图片。
现在我有两个 HTML 表单,其中有两个提交按钮,一个用于创建汽车,第二个用于上传汽车图像。我想将这两种表格合并为一个表格,管理员可以在其中输入汽车名称、生产年份,选择他想要上传的图片,然后通过一个按钮提交所有内容。
我不知道该怎么做,所以请查看下面的代码并告诉我需要进行哪些更改,我将不胜感激任何帮助
这是我的汽车型号:
public class Car
{
[Key]
public int CarID { get; set; }
public string Model { get; set; }
public int YearOfProduction { get; set; }
public string Price { get; set; }
public string Photo { get; set; }
public string AlternateText { get; set; }
[NotMapped]
public HttpPostedFileBase File { get; set; } //for image upload
}
这是我在“汽车”控制器中创建(汽车)操作方法:
[Authorize(Roles = "Administrator")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CarID,Model,YearOfProduction")] Car car)
{
if (ModelState.IsValid)
{
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
这是我在“汽车”控制器中上传(汽车图像)的操作方法:
[HttpPost]
public ActionResult Upload(Car picture)
{
if (picture.File.ContentLength > 0)
{
var fileName = Path.GetFileName(picture.File.FileName);
var path = Path.Combine(Server.MapPath("~/Images/Cars"), fileName);
picture.File.SaveAs(path);
}
return RedirectToAction("Index");
}
这是我用于创建汽车的 HTML 表单:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Car</h4>
<hr/>
@Html.ValidationSummary(true, "", new {@class = "text-danger"})
<div class="form-group">
@Html.LabelFor(model => model.Model, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.Model, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.Model, "", new {@class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.YearOfProduction, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.YearOfProduction, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.YearOfProduction, "", 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>
}
这是我用于上传汽车图像的 HTML 表单:
@using (Html.BeginForm("Upload", "Cars", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>File:</td>
<td><input type="file" name="File" id="File"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Upload"/></td>
</tr>
</table>
}