Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 Uploading file (POST) with one additional parameter

I am using this simple tutorial to upload a file in my MVC5 C# VS2015 project, and without requireing additional parameters in controllers action, file gets successfuly uploaded. Here are controllers action

    [HttpPost]
    public string UploadFile(HttpPostedFileBase file)
    {
        if (file.ContentLength <= 0)
            throw new Exception("Error while uploading");

        string fileName = Path.GetFileName(file.FileName);
        string path = Path.Combine(Server.MapPath("~/Uploaded Files"), fileName);
        file.SaveAs(path);
        return "Successfuly uploaded";
    }


and view's form for uploading

@using (Html.BeginForm("UploadFile", "Documents", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBox("file", "", new { type = "file" })
    <input type="submit" value="Dodaj fajl" />
}  

In that view, I have another variable called DocumentNumber, that I need to pass on to UploadFile action. I only guess that then header of my action would look like this: public string UploadFile(HttpPostedFileBase file, int docNo) if I wanted to pass that variable on, but I also don't know how to set this value in view's form. I tried adding: new { enctype = "multipart/form-data", docNo = DocumentNumber } without success. How do I pass DocumentNumber (that needs to be hidden, not visible) from my view to controller's action with post method?

like image 524
Monset Avatar asked Oct 18 '17 16:10

Monset


1 Answers

Add a parameter to your action method

[HttpPost]
public string UploadFile(HttpPostedFileBase file,int DocumentNumber)
{

}

and make sure your form has an input element with same name. It can be a hidden or visible. When you submit the form, the input value will be send with same name as of the input element name, which is matching to our action method parameter name and hence value will be mapped to that.

@using (Html.BeginForm("UploadFile", "Documents", FormMethod.Post,
                                     new { enctype = "multipart/form-data" }))
{
    @Html.TextBox("file", "", new { type = "file" })
    <input type="text" name="DocumentNumber" value="123"/ >
    <input type="submit" value="Dodaj fajl" />
}  

If you want to use the DocumentNumber property value of your model, you may simply use one of the helper methods to generate the input element with the value (which you should set in the GET action method)

@Html.TextBoxFor(s=>s.DocumentNumber)

or for the hidden input element

@Html.HiddenFor(s=>s.DocumentNumber)
like image 158
Shyju Avatar answered Oct 20 '22 20:10

Shyju