0

A beginner question - I have a HomeController, HomeModel and HomeView. When the user comes to the http://page/Home page, then Index method is executed and he can fill out some controls. After he clicks on a button (postback), the Process action is executed and in the case of an error, the application calls the ModelState.AddModelError method. Then the Index action is called again and I can display the error on the page.

This works OK, but the problem is that after the postback the new url is http://page/Home/Index instead of http://page/Home. Any idea how to prevent this?

PS - I tried this solution but then the new url was something like http://page/Home?...long string of serialized ModelState data...

My Controller:

[HttpGet]
public ActionResult Index(MyModel model)
{
    return View(model);
}

[HttpPost]
public ActionResult Process(MyModel model)
{
    if (...error...)
    {
        model.SetErrorState();
        ModelState.AddModelError("ProcessError", "error message");
        return View("Index", model);
    }
    else
    {
        // do something...
        model.SetSuccessState();
        return View("Index", model);
    }
}
Community
  • 1
  • 1
sventevit
  • 4,766
  • 10
  • 57
  • 89

1 Answers1

2

The problem is you're pushing to a new URL for the HttpPost action. If you change this to a HttpPost version of your Home Action you can neatly return to the page without the URL changing on error.

e.g.

[HttpGet]
public ActionResult Index(ImportData model)
{
    return View(model);
}

[HttpPost]
public ActionResult Index(MyModel model, FormCollection data)
{
    if (...error...)
    {
        model.SetErrorState();
        ModelState.AddModelError("ProcessError", "error message");
        return View(model);
    }
    else
    {
        // do something...
        model.SetSuccessState();
        return View(model);
    }
}
scgough
  • 5,099
  • 3
  • 30
  • 48
  • I made a mistake in my question - both methods expect one parameter with the same type 'MyModel'. If I correct this and apply your solution, then the compiler complains 'Type HomeController already defines a member called Index with the same parameter types'. – sventevit Apr 25 '17 at 20:08
  • updated @sventevit :) just add the (unused) `FormCollection` var to differentiate. – scgough Apr 25 '17 at 20:14
  • to @scgough - follow up question: how to do it when there are multiple buttons on the page and each should invoke own action? Then the action methods cannot all be named Index? – sventevit Apr 26 '17 at 12:50
  • @sventevit I would use ajax (jquery) to POST the form data on each button press (rather than submitting the page as normal) – scgough Apr 26 '17 at 14:59