开发者

MVC File upload validation

开发者 https://www.devze.com 2023-02-18 20:22 出处:网络
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.

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 (ne开发者_开发问答wFile.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


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

In controller accept not HttpPostedFile but your model class.


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")
0

精彩评论

暂无评论...
验证码 换一张
取 消