1

I have a simple situation where I have a page that uploads Files, for some importing. At the moment, all I have is a file upload input on my page.

this is what my get controller looks like

public ActionResult FileUpload()
{
    return View();
}

This is what my view looks like

@{
     ViewBag.Title = "FileUpload";
 }
<h2>FileUpload</h2>
<form action="/Home/FileUpload" method="post" enctype="multipart/form-data">
<input type="file" id="newFile" name="newFile" />
<input type="submit" id="submitButton" value="Submit" />
</form>

and this is what my post action looks like

[HttpPost]
    public ActionResult FileUpload(HttpPostedFileBase newFile)
    {
        if (newFile.ContentLength > 0)
        {
            //do stuff here
        }
        return View("Index");
    }

You will of course notice there is no mention of a model here as I cannot find a way to create a model for this situation. I would like to have some very basic validation, along the lines of 'please choose a file before you upload', thats all.

Is there a way to achieve this?!

Thanks in advance

Will

2 Answers 2

3

Create model class with string property newFile and put a Required on it.

In controller accept not HttpPostedFile but your model class.

Sign up to request clarification or add additional context in comments.

Comments

1

You should add the client side validation manually:

<input type="file" data-val="true" data-val-required="please select a file" name="file" />
@Html.ValidationMessage("file")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.