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

如果我这样写:

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

很管用。

但是在 Razor 中“@”不起作用,我犯了什么错误吗?

@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");
}
398688 次浏览

以下代码可以正常工作:

@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)的上下文中编写此代码,则应该在 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");
}