0

I have an MVC3 C#.Net web app. that has an import from Excel function. This function is performed in the Import method of the Rate controller. It is viewed in the Rate/Import view. When importing, some rows are successful, some are not. I am gathering the errors into a string[] array. The import is considered successful if one or more rows is successfully imported, therefore the app navigates back to the Proposal Edit view. I want to pass the informational errors back to the Proposal Edit view for display. Any ides how to do this?

1
  • By "the app navigates back to the Proposal Edit" do you mean you're doing a redirect after the form is submitted? If so, the only place you're going to be able to store information is in a database (passing an ID over to the other controller to go lookup the strings), in a session or in a cookie. The ViewBag/ViewData lifecycle ends with the life of the request. A redirect creates a new "Request" from the browser. Commented Feb 9, 2012 at 16:48

1 Answer 1

3

There are several ways.

TempData

This is available in your controller. TempData persists across a single redirect.

public ActionResult Process()
{
    // ... Process your rows, get array of errors back ...

    TempData["errors"] = errors;
    return RedirectToAction("Edit");
}

public ActionResult Edit()
{
    var errors = (IEnumerable<string>)TempData["errors"];  // Get the errors back.
    return View(errors);  // Pass into the view
}

ModelState

You could add these errors directly to the ModelState and then redisplay the edit form. It doesn't persist across a redirect.

public ActionResult Process()
{
    // ... Process your rows, get array of errors back ...

    for(var i = 0; i < errors.Length; i++)
    {
        ModelState.AddModelError("row" + i, errors[i]);
    }

    // Can't redirect here - ModelState doesn't persist.
    return View("Edit");
}

Then, in your edit view, just display the validation summary:

@Html.ValidationSummary("The following row errors occured:");

This will render this html. The class is the default one set by MVC.

<div class="validation-summary-errors">
    <span>The following row errors occured:</span>
    <ul>
        <li>...Error 1...</li>
        ... Other errors ...
    </ul>
</div>
Sign up to request clarification or add additional context in comments.

2 Comments

@leniency....thanks a lot. Good stuff! Question on the ModelState....how does the ModelState display the errors? Does there need to be more code in the Edit view? Thanks
@MikeTWebb Yes, the last line, @Html.ValidationSummary("The following row errors occured:"); is what displays any errors in the ModelState. Updated my answer with what that renders out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.