在通过Actions时丢失MongoDB的ObjectId值

本文关键字:MongoDB ObjectId Actions | 更新日期: 2023-09-27 17:49:24

在我的MVC Controller中,我有以下代码(添加对象后,我重定向用户编辑该对象):

    [PrivilegeRequirement("DB_ADMIN")]
    public ActionResult Add()
    {
        MongoDataContext dc = new MongoDataContext();
        var model = new ModelObj();
        dc.Models.Insert(model);
        return this.RedirectToAction("Edit", new { pId = model.Id, });
    }
    [PrivilegeRequirement("DB_ADMIN")]
    public ActionResult Edit(ObjectId? pId)
    {
        MongoDataContext dc = new MongoDataContext();
        var model = dc.Models.FindOneById(pId);
        if (model == null)
        {
            Session["error"] = "No model with this ID found.";
            return this.RedirectToAction("");
        }
        return this.View(model);
    }

然而,pId总是null,使得FindOneById总是返回null。我已经调试并确保从Add动作传递时Id有价值。此外,我尝试添加一个测试参数:

    [PrivilegeRequirement("DB_ADMIN")]
    public ActionResult Add()
    {
        MongoDataContext dc = new MongoDataContext();
        var model = new ModelObj();
        dc.Models.Insert(model);
        return this.RedirectToAction("Edit", new { pId = model.Id, test = 10 });
    }
    [PrivilegeRequirement("DB_ADMIN")]
    public ActionResult Edit(ObjectId? pId, int? test)
    {
        MongoDataContext dc = new MongoDataContext();
        var model = dc.Models.FindOneById(pId);
        if (model == null)
        {
            Session["error"] = "No model with this ID found.";
            return this.RedirectToAction("");
        }
        return this.View(model);
    }

当我调试时,我正确地收到Edit Action中的test参数值为10,但pId为空。请告诉我我做错了什么,以及如何解决这个问题?

在通过Actions时丢失MongoDB的ObjectId值

我怀疑ObjectId没有正确地序列化/反序列化。考虑到它不会产生一个伟大的WebAPI,我通常使用string,并通过Parse方法(或使用TryParse)在方法内转换为ObjectId:

public ActionResult Edit(string id, int? test)
{
    // might need some error handling here .... :)
    var oId = ObjectId.Parse(id);
}

您可以在ObjectId上使用ToString将其转换为用于调用的字符串:

var pId = model.Id.ToString();