How to write "Html.BeginForm" in Razor

kk-dev11 picture kk-dev11 · Dec 2, 2011 · Viewed 379.7k times · Source

If I write like this:

form action="Images" method="post" enctype="multipart/form-data"

it works.

But in Razor with '@' it doesn't work. Did I make any mistakes?

@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>
}

My controller looks like this:

[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");
}

Answer

Darin Dimitrov picture Darin Dimitrov · Dec 2, 2011

The following code works fine:

@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>
}

and generates as expected:

<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>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@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>
    }
}

As far as your server side code is concerned, here's how to proceed:

[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");
}