How to write "Html.BeginForm" in Razor

Formsasp.net Mvc-3Razor

Forms Problem Overview


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

Forms Solutions


Solution 1 - Forms

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkk-dev11View Question on Stackoverflow
Solution 1 - FormsDarin DimitrovView Answer on Stackoverflow