While Wonder how to validate the Upload control in a easy way, I find this solution as the best to do it, although lot of other ways are found.This is because you need not need to write much more code as a normal razor validation will solve the problem.
My View:
<div id="dvUpload" class="hide fieldControlContainer">
<div class="innerDivLeft">
<label class="blue">Upload Document:</label>
</div>
<div class="innerDivRight">
@Html.TextBoxFor(model => model.File, new { @class = "inputTextBox", type="file" })
@Html.ValidationMessageFor(model => model.File)
</div>
</div>
The magic lies with this line @Html.TextBoxFor(model => model.File, new { @class = "inputTextBox", type="file" }), here it will be rendered as a file upload control rather than a text because we are over riding the default behavior of input tag rendering by specifying it as type="file".
My Controller:
public ActionResult Index(HttpPostedFileBase file, MyModel model)
{
//Codes written here.
}
MyModel:
public class MyModel
{
[Required(ErrorMessage = "Please select file")] // this is for model validation
public HttpPostedFileBase File { get; set; }
}
Now your file upload validation will be checked like any other normal control.
No comments:
Post a Comment