dinotom
dinotom

Reputation: 5162

Model is null, even though populated model is passed in MVC 5 view

I am using RedirectToAction to pass a new model to a different view.

 [HttpPost]
    public ActionResult Index(BlogViewModel vm)
    {
        vm.IsValid = ModelState.IsValid;
        vm.LoadDropDowns();
        vm.ProcessRequest();
        if (vm.IsValid)
        {
            // NOTE: Must clear the model state in order to bind
            //       the @Html helpers to the new model values
            ModelState.Clear();
        }
        else
        {
            foreach (var item in vm.ValidationErrors)
            {
                ModelState.AddModelError(item.Key, item.Value);
            }
        }
        if (vm.EventCommand == "viewblog") 
        {
            //Note: this is a DIFFERENT model than the one passed into this method
            var bpvm = new BlogPostViewModel
            {
                Blog = vm.Entity,
                IsBlogPostListAreaVisible = true
            };
            return RedirectToAction("BlogPost", "Blogs", bpvm);
        }

        return View(vm);
    }

On stepping through the code, variable bpvm is fully populated with the correct data. And yes vm.EventCommand == "viewblog" is true so it should fall down to the redirect, which it does.

In the html

@model MachineryRestorations.Services.BlogService.BlogPostViewModel
@{
    ViewBag.Title = "BlogPost";
}

@using (Html.BeginForm())
{
     <!-- BEGIN HIDDEN FIELDS AREA -->
    @Html.HiddenFor(m => m.BlogPost.BlogPostId)
    @*@Html.HiddenFor(m => m.EventArgument)*@
    <!-- END HIDDEN FIELDS AREA -->
    if (Model.IsBlogPostListAreaVisible)
    {
       <!-- code removed for brevity -->
    }
}

EDIT: And the code in the controller

public ActionResult BlogPost(BlogPostViewModel bpvm)
{
    return View(bpvm);
}

I am getting an error on Model.IsBlogPostListAreaVisible, this is due to the fact that with a breakpoint on the BeginForm, I see that Model is null. How is that when I'm passing it a perfectly valid model?

Upvotes: 1

Views: 258

Answers (2)

cranfan
cranfan

Reputation: 131

You're returning back BlogViewModel not BlogPostViewModel. If

if (vm.EventCommand == "viewblog")

is correct then return RedirectToAction("BlogPost", "Blogs", bpvm); only Redirects to Action which we're not seeing inner code

Upvotes: 1

BDZ
BDZ

Reputation: 43

Make sure the ViewModel BlogPostViewModel is populated in the action method you're redirecting to. I think it should be BlogPost(BlogPostViewModel vm).

Upvotes: 0

Related Questions