2016-08-04 25 views
0

我有顧客類MVC設定值到整數對象的屬性在會話

public class Customer 
{ 
    public string Name { get; set; } 
    public string Surname{ get; set; } 
    public string Email { get; set; } 
    public string MobilePhone { get; set; } 

    public int Type { get; set; } 
} 

在HomeController中的索引方法,我已經創建客戶的實例,並且設置值,以properties.Then我其存儲在會話在同一控制器中的Index(HttpPost)方法中獲取對象。在索引(HttpPost)方法中,我可以正確地獲取除「類型」屬性以外的所有屬性值。當我從會話中獲取Customer對象時,此對象的'Type'屬性始終等於0.

public ActionResult Index(string id, string co) 
{ 
    Customer cust = new Customer(); 
    cust.Name = "customer"; 
    cust.Surname = "test"; 
    cust.EMail = "[email protected]"; 
    cust.Type=2; 

    Session["customer"] = cust; 

    return View(customer); 
} 

[HttpPost] 
public ActionResult Index() 
{ 
    Customer customer = new Customer(); 
    if (Session["customer"] != null) 
    { 
     customer = (Customer)Session["customer"]; 
    } 
    //customer.Type is equal 0 
} 

可能是什麼原因以及如何避免?

感謝答覆提前

+0

難道你確定'Session [「customer」]'不是'null'?因爲如果是這樣,那麼您將擁有使用所有默認值設置爲其屬性的初始「客戶」。 – juharr

+0

是的。其他屬性不爲null或爲空,它們具有我設置的值。 –

+0

你的代碼對我來說看起來非常好。你確定這是你項目中的確切代碼嗎?沒有類型(在會話密鑰中)? – Shyju

回答

1

你的代碼看起來OK(除cust.EMail錯別字 - >cust.Emailreturn View(customer) - >return View(cust))我甚至已將此添加到我的項目,它工作得很好......