asp.net-core-mvcviewmodel

How to redirect with viewmodel


In a GET action method, based in some condition, I need to either return the view, or redirect to another action method that receives a view model via POST. This second action method view is strongly typed to a model.

The code below is not working: when the condition is true, it redirects to the second action method and this runs OK, but right after that, it returns to the last line of the first method.

// GET: MyController/Info
public async Task<IActionResult> Info(int someId, string something) 
{
    // create viewmodel
    SomeViewmodel vm = new SomeViewmodel() 
                           {
                               Id = someId,
                               Name = something
                           };

    // depending on some condition, either redirect to a post method, or return view
    if (somecondition) 
    {
        return await this.Info2(vm);
    }
    else 
    {
        return View(vm);
    }
}   //PROBLEM HERE - if condition is true, it returns here after Info2()... 

public async Task<IActionResult> Info2(SomeViewmodel vm) 
{
    // ...
    MyModel mdl = new MyModel() 
                  {
                      // ...
                  }
    return View(mdl);
}

The error I get is :

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Castle.Proxies.MyModelProxy', but this ViewDataDictionary instance requires a model item of type 'MyApp.MvcApp.ViewModel.SomeViewModel'.


Solution

  • If it's necessary redirect to another action method use RedirectToAction():

    // depending on some condition, either redirect to a post method, or return view
    if (somecondition) 
    {
        return await RedirectToAction(nameof(Info2), vm);
    }    
    return View(vm);    
    

    Note: When your directly return this.Info2(vm); from the action method the MVC will use signature of the Info view data model. This is why you got the data binding error.