如何在Razor中编写“Html.BeginForm”

如果我这样写:

form action =“Images”method =“post”enctype =“multipart / form-data”

有用。

但在剃刀与'@'它不起作用。 我犯了什么错误吗?

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.ValidationSummary(true) <fieldset> Select a file <input type="file" name="file" /> <input type="submit" value="Upload" /> </fieldset> } 

我的控制器看起来像这样:

 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Upload() { foreach (string file in Request.Files) { var uploadedFile = Request.Files[file]; uploadedFile.SaveAs(Server.MapPath("~/content/pics") + Path.GetFileName(uploadedFile.FileName)); } return RedirectToAction ("Upload"); } 

下面的代码工作正常:

 @using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.ValidationSummary(true) <fieldset> Select a file <input type="file" name="file" /> <input type="submit" value="Upload" /> </fieldset> } 

并按预期生成:

 <form action="/Upload/Upload" enctype="multipart/form-data" method="post"> <fieldset> Select a file <input type="file" name="file" /> <input type="submit" value="Upload" /> </fieldset> </form> 

另一方面,如果您正在编写其他服务器端构造(如ifforeach的上下文内的代码, if应该在using前删除@ 。 例如:

 @if (SomeCondition) { using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.ValidationSummary(true) <fieldset> Select a file <input type="file" name="file" /> <input type="submit" value="Upload" /> </fieldset> } } 

至于你的服务器端代码,这里是如何进行 :

 [HttpPost] public ActionResult Upload(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/content/pics"), fileName); file.SaveAs(path); } return RedirectToAction("Upload"); }