kk-*_*v11 130 forms razor asp.net-mvc-3
如果我这样写:
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>
}
Run Code Online (Sandbox Code Playgroud)
我的控制器看起来像这样:
[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");
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 195
以下代码工作正常:
@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>
}
Run Code Online (Sandbox Code Playgroud)
并按预期生成:
<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>
Run Code Online (Sandbox Code Playgroud)
另一方面,如果您在其他服务器端构造的上下文中编写此代码,if或者foreach您应该删除@之前的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>
}
}
Run Code Online (Sandbox Code Playgroud)
就服务器端代码而言,以下是如何继续:
[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");
}
Run Code Online (Sandbox Code Playgroud)