Copied to clipboard

Flag this post as spam?

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


  • DbdCopilotTrial 2 posts 32 karma points
    Feb 21, 2023 @ 16:52
    DbdCopilotTrial
    0

    Re-Populating form which submits to a SurfaceController

    I have googled this but have found no good answer.

    I have a form which submits to an action in a SurfaceController.

    The action does some things to the form data and if all is OK redirects. If it finds issues with the data it populates the modelstate errors collection and then calls

    return CurrentUmbracoPage();

    However this results in the form being rendered blank with my error message from the ModelState displayed at the top.

    I would like to change this so that when the form re-renders it is populated with the users previous form submission

    in normal MVC this would be

    [HttpPost]
    public async IActionResult SomePostHandler(ExampleViewModel vm)
    {
        if (SometingIsWrong)
        {
          ModelState.AddModelError("ExampleViewModel", "Error message");
            return View(vm);  
        }
    }
    

    With the view having a reference to the viewModel like this

    @model ExampleViewModel

    and then the form fields being like this:

    <input type="text" asp-for="ExampleViewModel.Name"/>
    

    Any pointers would be greatly appreciated - either Im missing something really basic or Im doing something wrong (Is a surface controller even the right way to do it?)

  • Dave Woestenborghs 3504 posts 12133 karma points MVP 8x admin c-trib
    Feb 22, 2023 @ 10:07
    Dave Woestenborghs
    100

    Hi,

    You can pass the posted form back to the view using viewdata.

    [HttpPost]
    public async IActionResult SomePostHandler(ExampleViewModel vm)
    {
        if (SometingIsWrong)
        {
          ModelState.AddModelError("ExampleViewModel", "Error message");
    this.ViewData["model"] = vm;
           return this.CurrentUmbracoPage();
        }
    }
    

    And then in your view can get read it from the view data.

    @{
     var vm= this.ViewData["model"] as ExampleViewModel ?? new ExampleViewModel ();
    }
    

    Dave

  • DbdCopilotTrial 2 posts 32 karma points
    Mar 02, 2023 @ 17:28
    DbdCopilotTrial
    0

    Hi,

    Thanks for the response, I ended up taking the post out of the surface controller and using a renderController instead with route hijacking - that let me specify a strongly typed model which I populate and pass back to the view.

    Im not a massive fan of ViewData/TempData/ViewBag etc I've always been uneasy about them being untyped and having to cast them in the view.

    Marking your answer as the solution as if I'd stuck with the SurfaceController as in the OP it would be the best way forward.

    Thanks

Please Sign in or register to post replies

Write your reply to:

Draft