1

I am uploading file using asp.net mvc with file upload required but unable to upload file using this. How to make file upload required with validation using ASP.NET MVC?

Here is my Model class code.

public class Slider
    {
        public int SliderId { get; set; }

        [Required]
        public string Title { get; set; }
        [Required]
        public string FileURL { get; set; }

    }

Here is my Create Controller:

[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create([Bind(Include = "SliderId,Title,FileURL")] HttpPostedFileBase file, Slider slider)
{
    if (ModelState.IsValid)
    {

        if (file != null)
        {
            string fil = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(Server.MapPath("~/Content/Uploads/Slider/"), fil);
            file.SaveAs(path);
            slider.FileURL = "/Content/Uploads/Slider/" + file.FileName;
        }              

        db.Sliders.Add(slider);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(slider);
}

Here is my View:

@model Test.Models.Slider

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}



@using (Html.BeginForm("Create", "SliderManager", FormMethod.Post, new { enctype = "multipart/Form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h2>Create</h2>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Title,"Title*", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-2">
                <label for="file">Upload Image  for Slide*:</label>
            </div>
            <div class="col-md-10">
                <input type="file" name="file" id="file" style="width:50%" />

            </div>

        </div>
           <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
ctest
  • 13
  • 1
  • 3
  • Have a look into this. http://stackoverflow.com/questions/6388812/how-to-validate-uploaded-file-in-asp-net-mvc – Chandrasekar Kesavan Nov 08 '15 at 17:56
  • You have no code that checks for file being uploaded, the only part you have if file is present. So add check if file is not there add validation error and that will fail your your viewstate – cpoDesign Nov 09 '15 at 08:57
  • @cpoDesign How to check file being uploaded on above code? – ctest Nov 10 '15 at 16:17

2 Answers2

4

Changes to make

1st model

  public class Slider
{
    public int SliderId { get; set; }

    [Required]
    public string Title { get; set; }

    public string FileURL { get; set; }
}

Removed required on file Url as this is not coming from user but you should be populating it

2nd Upload action

[HttpPost]
    [ValidateAntiForgeryToken]
    [ValidateInput(false)]
    public ActionResult Create(HttpPostedFileBase file, Slider slider)
    {
        //Add validation if file is not present and fail model
        if (file == null)
        {
            ModelState.AddModelError("FileURL", "Please upload file");
        }

        if (ModelState.IsValid)
        {

            if (file != null)
            {
                string fil = System.IO.Path.GetFileName(file.FileName);
                string path = System.IO.Path.Combine(Server.MapPath("~/Content/Uploads/Slider/"), fil);
                file.SaveAs(path);
                slider.FileURL = "/Content/Uploads/Slider/" + file.FileName;
            }

            //db.Sliders.Add(slider);
            //db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View("~/Views/Home/Index.cshtml", slider);
        //return View(slider);
    }

Also I am not sure why you have specified additional bindings, but I guess you had some reason for that

3rd the view

    @using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/Form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h2>Create</h2>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Title, "Title*", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-2">
                <label for="file">Upload Image  for Slide*:</label>
            </div>
            <div class="col-md-10">
                <input type="file" name="file" id="file" style="width:50%" />
                @Html.ValidationMessageFor(x=>x.FileURL)
            </div>

        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
    }

I have added validation message. This validation message of course can have its own property and I would modify it so it fits with your business logic.

<input type="file" name="file" id="file" style="width:50%" />
            @Html.ValidationMessageFor(x=>x.FileURL)
cpoDesign
  • 8,953
  • 13
  • 62
  • 106
1

I think the solution from this tutorial is better because it doesn't need an extra property:

https://www.aspsnippets.com/Articles/Fileupload-validation-using-Model-Data-Annotations-in-ASPNet-MVC.aspx

Model:

public class FileModel
{
    [Required(ErrorMessage = "Please select file.")]
    public HttpPostedFileBase PostedFile { get; set; }
}

View:

@model FileUpload_Validation_MVC.Models.FileModel

@{
    Layout = null;
}
    <div>
            @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                <span>Select File:</span>
                @Html.TextBoxFor(m => m.PostedFile, new { type = "file"})
                <br/>
                @Html.ValidationMessageFor(m => m.PostedFile, "", new { @class = "error" })
                <hr/>
                <input type="submit" value="Upload"/>
            }
        </div>
tala9999
  • 1,540
  • 2
  • 15
  • 25