RedirectToAction(..) with complex deep object fails

前端 未结 4 1827
生来不讨喜
生来不讨喜 2021-01-04 13:18

I\'m trying to pass an object from one controller action to another. The object that I\'m passing around looks more or less like this:

public class Person
{
         


        
4条回答
  •  离开以前
    2021-01-04 14:12

    Do you really need to Redirect to the other action? RedirectToAction causes a brand new http request, which is why TempData works. Couldn't you just call the Result action directly like this?

    public ActionResult Index()
    {
        // Complex object structure created
        Person person = new Person();
        person.PhoneNumbers = new List();
        person.PhoneNumbers.Add("12341324");
    
        return Result(person);
    
    }
    

    Edit Unless your app is doing more than what you've shown in the question, it doesn't look like you really need the Index action. You could move the code that creates a new person into a private CreatePerson method. In your Result action if person is null, then call the CreatePerson method. The Index action could be eliminated altogether, but that would require modifying your routes. Or just let return RedirectToAction("Result", "Dialog"); be the only line of code in your Index action.

    Actually, following MVC separation of concerns, that CreatePerson method should probably be a method inside your model code. The controller shouldn't need to contain the logic of creating a new Person. That really belongs in the model.

提交回复
热议问题