当重定向到另一个操作方法时,模型绑定对象属性在传递时变为NULL

时间:2018-08-17 11:52:55

标签: asp.net-mvc model-binding

我正在尝试学习在MVC应用程序中绑定复杂的对象。下面是我的课

public class StrongUser
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public Country myCountry { get; set; }
    public List<Country> CountryList { get; set; }
    public StrongUser()
    {
        firstName = "Naveen";
        lastName = "Verma";
        myCountry = Country.ListOfCountries()[0];
        CountryList = Country.ListOfCountries();
    }

    public static StringBuilder Print(StrongUser user2)
    {
        StringBuilder sr = new StringBuilder();
        sr.AppendLine("First Name=" + user2.firstName);
        sr.AppendLine("<br>");
        sr.AppendLine("Last Name=" + user2.lastName);
        sr.AppendLine("<br>");
        sr.AppendLine("My Country Name=" + user2.myCountry.Name);
        sr.AppendLine("<br>");
        sr.AppendLine("My Country Continent=" + user2.myCountry.Continent);
        sr.AppendLine("<br>");
        sr.AppendLine("My Country List:");
        sr.AppendLine("<br>");
        foreach (Country c in user2.CountryList)
        {
            sr.AppendLine("<br>");
            sr.AppendLine("Name=" + c.Name);
            sr.AppendLine("<br>");
            sr.AppendLine("Continent=" + c.Continent);
        }
        return sr;
    }
}

public class Country
{ public int Id { get; set; }
  public string Name { get; set; }
  public string Continent { get; set; }

    public static List<Country> ListOfCountries()
    {
        return new List<Country>()
        {
            new Country(){Id=1, Name ="India",Continent="Asia"},
            new Country(){Id=2,Name="USA",Continent="North America"},
            new Country(){Id=3,Name="Japan",Continent="Asia"},
            new Country(){Id=4,Name="UK",Continent="Asia-Pacific"},
            new Country(){Id=5,Name="Australia",Continent="Australia"},
            new Country(){Id=6,Name="China",Continent="Asia"}

        };
    }

}

我正在使用以下控制器

    [HttpGet]
     public ActionResult EditBindCheck()
    {
        return View(new StrongUser());
    }

    [HttpPost]
    public ActionResult EditBindCheck(StrongUser user)
    {
//here all the values are properly binded to **user** object

        return RedirectToAction("PrintStrongUser", user);
    }

    public StringBuilder PrintStrongUser(StrongUser user2)
    {

        return StrongUser.Print(user2);
    }

EditBindCheck 方法中发布表单时,所有值均已正确绑定到 user 对象。 但是在传递给 PrintStrongUser 时,user2.firstName和user2.lastName与用户对象中的相同,但user2.myCountry和user2.CountryList为 NULL

我不明白为什么对象在传递给另一个ActionMethod时更改了其值?

0 个答案:

没有答案