Travis Heeter
Travis Heeter

Reputation: 14054

Showing Form Errors with MVC

I have a form that uploads image files and checks that they're jpgs:

// CarAdmin/Index.cshtml
@model MySite.Models.Car
@using (Html.BeginForm("CarImageUpload", "Car", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="text" name="imageInfo" />
    <input type="submit" value="OK" />
}
<form action="CarAJAX" method="post" name="CarAdminForm">
    <input name="Make" value="@Model.Name/>
    <input type="submit" value="Update Car Info">
</form>

// CarController.cs
[HttpPost]
public ActionResult CarImageUpload(HttpPostedFileBase file)
{
    ValidateImageFile V = new ValidateImageFile(file); // checks that the file is a jpg
    List<String> Validity = V.Issues;

    if (Validity.Count == 0)
    {
        file.SaveAs(V.FilePath);
    }
    else 
    {
        Response.Write(String.Join("<br>", Validity.ToArray()); // THIS IS PROBLY WRONG
    }
    RedirectToAction("CarAdmin");
}
public ActionResult CarAdmin()
{
    return View("CarAdmin/Index.cshtml");
}

If the ValidateImageFile class finds a problem, I want to:

However, I'm not sure how to manipulate forms from the Controller, and my Response.Write is not sending back anything (that I can see - but I'm not sure how to access that).

I have a few ideas on how to accomplish this, but they seem like a duct tape job, rather than best practice.

Upvotes: 4

Views: 138

Answers (1)

Alexandre St-Amant
Alexandre St-Amant

Reputation: 86

User Darian Dimitrov answered a question very similar to your's, his solution should point you in the right direction.

Is there a way to validate incoming HttpPostedFilebase files in MVC 2?

Another good resource for what your are trying to do is:

http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/

Your View may look like:

// CarAdmin/Index.cshtml
@model MySite.Models.CarUploadViewModel
@using (Html.BeginForm("CarImageUpload", "Car", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="ImageUpload" />
    <input type="text" name="ImageInfo" />
    <input type="submit" value="OK" />
}
<form action="CarAJAX" method="post" name="CarAdminForm">
    <input name="Make" value="@Model.Name/>
    <input type="submit" value="Update Car Info">
</form>

Your Model may look like:

public class CarUploadViewModel
{
    [Required]
    public string ImageInfo{ get; set; }

    [DataType(DataType.Upload)]
    HttpPostedFileBase ImageUpload { get; set; }
}

Your controller may look like:

[HttpPost]
public ActionResult CarImageUpload(CarUploadViewModel model)
{
    ValidateImageFile validity = new ValidateImageFile(model.ImageUpload); // checks that the file is a jpg
    List<String> issues = validity.Issues;

    if (issues.Count > 0)
    {
        // TODO: Add more descriptive issue messages
        ModelState.AddModelError("ImageUpload", "There was an issue.");
    }

    if(ModelState.IsValid)
    {
        model.ImageUpload.SaveAs(V.FilePath);
        RedirectToAction("CarAdmin");
    }

    return View(model);
}

Basically, what you want to do is create a Model for your form, check it for validity, and if it's not valid, return the model with validation errors to the view.

To add custom errors to a model, you use:

ModelState.AddModelError("MyField", "Custom error message here");

And output it to the view like:

@Html.ValidationMessage("MyField");

Upvotes: 2

Related Questions