Steven
Steven

Reputation: 18859

ValidationSummary doesn't display errors

I have a page that charges a credit card. When I attempt to charge the card, I'd like to redisplay the page if I get an error back as a response.

Here's my controller method:

[HttpPost]
public ActionResult Charge(CreditCardViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var request = new AuthorizationRequest(viewModel.CreditCardNumber,
            viewModel.ExpirationDate.Value.ToString("MMyy"),
            viewModel.Amount.Value, "");
        var gate = new Gateway("XXXXXXXXX", "XXXXXXXXX", true);
        var response = gate.Send(request);

        if (!response.Approved)
        {
            ModelState.AddModelError("", response.Message);
            return View(viewModel);
        }
        else
        {
            viewModel.ResponseMessage = response.Message;
            return View("Results", viewModel);
        }
    }
    return View(viewModel);     // validation error, so redisplay same view
}

And my view:

<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm("Charge", "CreditCard", FormMethod.Post)) { %>

    <div class="editor-label"><%: Html.LabelFor(m => m.CreditCardNumber) %></div>
    <div class="editor-field">
        <%: Html.TextBoxFor(m => m.CreditCardNumber)%>
        <%: Html.ValidationMessageFor(m => m.CreditCardNumber)%>
    </div>

    <div class="editor-label"><%: Html.LabelFor(m => m.ExpirationDate) %></div>
    <div class="editor-field">
        <%: Html.TextBoxFor(m => m.ExpirationDate)%>
        <%: Html.ValidationMessageFor(m => m.ExpirationDate)%>
    </div>

    <div class="editor-label"><%: Html.LabelFor(m => m.Amount) %></div>
    <div class="editor-field">
        <%: Html.TextBoxFor(m => m.Amount)%>
        <%: Html.ValidationMessageFor(m => m.Amount)%>
    </div>

    <div class="buttons">
        <input type="submit" value="Charge Amount" />
    </div> 

    <% Html.ValidationSummary(false); %>

<% } %>

The code works correctly - if I get an error back as a response, the view is reloaded. The only problem is that no error is displayed by the validation summary.

One strange thing is that if I change the AddModelError line to:

ModelState.AddModelError("CreditCardNumber", response.Message);

It will show the error next to the CreditCardNumber textbox. But I'd like to display the error in the summary below the form, as sometimes the error may not be with the credit card.

Upvotes: 1

Views: 3531

Answers (2)

MorioBoncz
MorioBoncz

Reputation: 920

Try this (pay attention to colon) as it returns MvcHtmlstring:

<%: Html.ValidationSummary(false) %>

It is ok to give empty string, it will be treated as not field error.

Upvotes: 3

Mikael &#214;stberg
Mikael &#214;stberg

Reputation: 17146

Add another ValidationMessage output.

<%= Html.ValidationMessage("GatewayError") %>

And set the error message accordingly

ModelState.AddModelError("GatewayError", response.Message);

Upvotes: 2

Related Questions