Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Tom Engan 430 posts 1173 karma points
    Dec 15, 2017 @ 10:02
    Tom Engan
    0

    SurfaceController: Return of URL that maintains ModelState

    Which method is simplest (best practice) to maintain ModelState like with return CurrentUmbracoPage();

    I want a return method in the surface controller that returns ModelState, but Redirect does not retain ModelState. This should be a normal scenario, but can't find equivalent option for return method. The url contains parameter and anchor so the string is correct (/turlister?partial=LoginForm#tab-1)

    if (!ModelState.IsValid)
         // return CurrentUmbracoPage ();   <= ModelState is maintained
         return Redirect(string.Format("{0}#tab-1", "/turlister?partial=LoginForm"));
    
  • Alex Skrypnyk 5908 posts 22603 karma points MVP 4x admin c-trib
    Dec 15, 2017 @ 10:54
    Alex Skrypnyk
    0

    Hi Tom

    I'm not sure that it's right way to handle url fragments - Redirect(string.Format("{0}#tab-1", "/turlister?partial=LoginForm"));

    Maybe it's better to use return CurrentUmbracoPage (); and pass some value to client in the ViewData and use this data in js for scrolling the page to

    string.Format("{0}#tab-1", "/turlister?partial=LoginForm")
    

    What do you think? Is it a solution?

    Thanks,

    Alex

  • Tom Engan 430 posts 1173 karma points
    Dec 15, 2017 @ 11:25
    Tom Engan
    100

    Thanks for your reply. I actually get the correct url with string.Format("{0}#tab-1", "/turlister?partial=LoginForm"), and now I've also found a solution that works

    base controller

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (TempData["ModelState"] != null && !ModelState.Equals(TempData["ModelState"]))
            ModelState.Merge((ModelStateDictionary)TempData["ModelState"]);
    
        base.OnActionExecuted(filterContext);
    }
    

    ActionResult

    if (!ModelState.IsValid) {
        TempData["ModelState"] = ModelState;
        return Redirect(string.Format("{0}#tab-1", "/turlister?partial=LoginForm")); }
    

    Now I can validate fields as before, both on the client side and on the server side.

    I found the solution here: https://stackoverflow.com/questions/658747/how-do-i-maintain-modelstate-errors-when-using-redirecttoaction

    What is by the way best practice regarding where to put OnActionExecuted, because I intend to use the method in several controllers?

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies