Copied to clipboard

Flag this post as spam?

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


  • Lee 1130 posts 3088 karma points
    Jun 20, 2013 @ 20:47
    Lee
    1

    Passing Model Back With CurrentUmbracoPage And Surface Controllers?

    Using MVC, if you post to an action do whatever logic you need. And want to pass a model back, this doesn't seem possible with Umbraco MVC?

    In a normal MVC app I can just go

    var viewModel = new myCoolViewModel();
    return View(viewModel)

    But it doesn't look like you can do this with Umbraco MVC? If not, when posting a form and the validation is wrong. How to you keep the form state without being able to return a viewModel?

  • milos 1 post 21 karma points
    Jul 08, 2013 @ 11:33
  • Kevin Lawrence 183 posts 350 karma points
    Jul 15, 2013 @ 16:14
    Kevin Lawrence
    1

    I too am finding this situation a little limiting, here is my fix for when you want to redirect to the current page but pass in a partial view to render and an optional model, this is an example ChangePassword Post action:

          [NotChildAction]
    [HttpPost]
    public ActionResult ChangePassword(ChangePasswordViewModel model)
    {
    if (!ModelState.IsValid) return CurrentUmbracoPage();

    var user = Membership.GetUser();
    if (user == null) return RedirectToCurrentUmbracoPage("Membership/UserNotLoggedIn");

    if (!user.ChangePassword(model.Password, model.NewPassword))
    {
    ModelState.AddModelError("Password", "The password change failed, please ensure your current password is correctly entered");
    return CurrentUmbracoPage();
    }

    return RedirectToCurrentUmbracoPage("Membership/PasswordChanged");
    }

    This is a new RedirectToCurrentUmbracoPage method I created:

          protected ActionResult RedirectToCurrentUmbracoPage(string viewName, object model = null)
    {
    TempData["surface-view-name"] = viewName;
    TempData["surface-model-current"] = model;

    return RedirectToCurrentUmbracoPage();
    }

    ...and finally this is the Macro Partial View:

    @{
    var model = Cornwall.Model();
    var view = Cornwall.View();
    }

    @if (!string.IsNullOrEmpty(view))
    {
    @Html.Partial(string.Format("/Views/{0}.cshtml", view), model)
    }
    else
    {
    @Html.Action("ChangePassword", "Membership")
    }

    The 2 lines at the beginning simply check for the existance of the view and model in the TempData and if found this view will render the necessary view passing in the model too, this must be a partial view.  If there is no view specified then it simply renders the default child action.

    It's not perfect but it means you can dictate which partial view you want rendered without having to clutter your macro partial with too much logic.

Please Sign in or register to post replies

Write your reply to:

Draft