Water Cooler v2
Water Cooler v2

Reputation: 33880

ModelStateErrors not showing up in ValidationSummary

I have two validations in my action like so:

if (viewModel.IssuePDFFile == null || viewModel.IssuePDFFile.ContentLength == 0)
{
    ModelState.AddModelError("", "Please select a file to upload.");

    if (selectedJournalId > 0)
    {
        return RedirectToAction("CreateNewIssue", new { journalId = selectedJournalId });
    }
    else
    {
        return RedirectToAction("CreateNewIssue", 
            new { journalId = selectedJournalId, journalName = viewModel.JournalName });
    }
}

var fileInfo = new FileInfo(viewModel.IssuePDFFile.FileName);
if (!StaticData.AcceptedContentTypes.Contains(viewModel.IssuePDFFile.ContentType, 
                                    StringComparer.InvariantCultureIgnoreCase) || 
    !fileInfo.Extension.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase))
{
    ModelState.AddModelError("IssuePDFFile", "You can only select a PDF file.");

    if (selectedJournalId > 0)
    {
        return RedirectToAction("CreateNewIssue", new { journalId = selectedJournalId });
    }
    else
    {
        return RedirectToAction("CreateNewIssue", new { journalId = selectedJournalId, 
                            journalName = viewModel.JournalName });
    }
}

And in my view, I have this:

@using (Html.BeginForm(...)
{
    @Html.ValidationSummary(false, "", new { @class = "text-danger" })

    @*File*@
    <div class="form-group">
        @Html.LabelFor(model => model.IssuePDFFile, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-12">
            <input type="file" id="File" name="issuePDFFile" placeholder="Select a file to upload" />
            @Html.ValidationMessageFor(model => model.IssuePDFFile, "", new { @class = "text-danger" })
        </div>
    </div>

    ...
}

Please note that the excludePropertyErrors argument in the call to the @Html.ValidationSummary extension is set to false in the hope that errors that I myself add to the model state errors collection using keys other than my property names will also show up in the summary.

However, the two error messages shown in the code snippet above do not show up anywhere, neither in the validation summary, nor in the ValidationFor place where I think at least one of them, the one I have added a key for, should show up?

Upvotes: 1

Views: 71

Answers (1)

Carl
Carl

Reputation: 2295

It looks like you are performing a redirect after writing errors to your modelstate. Redirecting will loose the modelstate, as it is only valid for the lifetime of the request, which ends when you redirect.

The solution is to

return View(Model) //customise as necessary

rather than your current

return RedirectToAction()

Writing the response back to the client within the same reuqest will mean the Modelstate is available to use, and display the errors.

Upvotes: 3

Related Questions