【问题标题】:MVC set value to integer property of an object in sessionMVC 将值设置为会话中对象的整数属性
【发布时间】:2016-08-04 22:15:25
【问题描述】:

我有客户类

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) 方法中,我可以正确获取除“类型”属性之外的所有属性值。当我从会话中获取客户对象时,该对象的“类型”属性始终等于 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
}

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

感谢提前回复

【问题讨论】:

  • 您确定Session["customer"] 不是null?因为如果是这样,那么您将拥有您创建的初始Customer,并将所有默认值设置为它的属性。
  • 是的。其他属性不为 null 或为空,它们具有我设置的值。
  • 您的代码在我看来完全没问题。您确定这是您项目中的确切代码吗?没有类型(在会话密钥中)?

标签: c# asp.net-mvc session


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 2014-06-30
    • 2022-08-24
    • 1970-01-01
    • 2013-06-11
    • 2016-11-18
    • 2014-05-15
    • 2015-10-22
    • 2021-07-19
    相关资源
    最近更新 更多