MVC将值设置为会话

时间:2016-08-04 13:04:16

标签: c# asp.net-mvc session

我有客户类

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的Index方法中,我创建了一个Customer实例并设置了属性值。然后我将它存储在session中,以获取同一控制器中Index(HttpPost)方法中的对象。在Index(HttpPost)方法中,我可以正确获取所有属性值,除了' Type'属性。当我从会话中获得Customer对象时,'键入'该对象的属性始终等于0.

public ActionResult Index(string id, string co)
{
    Customer cust = new Customer();
    cust.Name = "customer";
    cust.Surname = "test";
    cust.EMail = "test@test.com";
    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
}

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

感谢您提前回复

1 个答案:

答案 0 :(得分:1)

您的代码看起来不错(cust.EMail - > cust.Emailreturn View(customer) - > return View(cust)中的拼写错误除外)我甚至将此添加到我的项目中并且效果很好良好...