How to write "Html.BeginForm" in Razor

395,934

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");
}
Share:
395,934
kk-dev11
Author by

kk-dev11

Learning..

Updated on July 08, 2022

Comments

  • kk-dev11
    kk-dev11 almost 2 years

    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");
    }
    
  • kk-dev11
    kk-dev11 over 12 years
    thanks. Look at the controller I updated in my question. It doesn't work with the Razor code..
  • Darin Dimitrov
    Darin Dimitrov over 12 years
    @user1076915, what does it doesn't work mean? Could you be a little more specific. I have updated my answer with a sample code of how your controller action could look like. If you are unable to get the uploaded file in the controller action that could mean that you have nested <form> tags (which is not allowed in HTML) or you might be using some javascript which hijacks the normal form submission and does an AJAX request which doesn't work with file uploads.
  • kk-dev11
    kk-dev11 over 12 years
    I used your controller action and the razor '@using'.. but it displays --> Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
  • Darin Dimitrov
    Darin Dimitrov over 12 years
    @user1076915, when do you get this error message? When you want to render the upload form or when you submit the form? In the first case ensure that you have a GET Upload action that will serve the Upload.cshtml view containing this code: public ActionResult Upload() { return View(); }. So make sure you have a controller called UploadController containing the two Upload actions : one for serving the form and the other for processing the submission.
  • kk-dev11
    kk-dev11 over 12 years
    I have both of them. But I got this problem only when I submit the picture I browsed.
  • Darin Dimitrov
    Darin Dimitrov over 12 years
    @user1076915, do you have some custom routes or you are using the default setup? How exactly is called your controller? Please post your full controller code.
  • kk-dev11
    kk-dev11 over 12 years
    When I upload a picture, It shows.. "The connection was reset" The connection to the server was reset while the page was loading. What could be the problem?
  • Darin Dimitrov
    Darin Dimitrov over 12 years
    @Freetalk13, the size of the file you are trying to upload. There's a default limit of 4MB which you could increase in web.config by using the <httpRuntime> element: <httpRuntime maxRequestLength="102400" executionTimeout="3600" executionTimeout="3600" />.
  • Frédéric De Lène Mirouze
    Frédéric De Lène Mirouze over 6 years
    Works, but in a POST context I suggest to add: @Html.AntiForgeryToken();