1

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'.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

nice! it works (except I had to remove the "await" part... so it finally worked with return RedirectToAction(nameof(Info2), vm);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.