c# - Lose MongoDB ObjectId value when passing through Actions -
in mvc controller
, have code (after adding object, redirect user edit object):
[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 id found."; return this.redirecttoaction(""); } return this.view(model); }
however, pid null, making findonebyid
return null. have debugged , made sure id had value when passing add
action. moreover, tried adding testing parameter:
[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 id found."; return this.redirecttoaction(""); } return this.view(model); }
when debug, received test
parameter in edit
action value of 10 correctly, pid null. please tell me did wrong, , how solve problem?
i suspect objectid not serializing/deserializing correctly. given doesn't make great webapi anyway, use string
, convert within method objectid
via parse
method (or use tryparse
):
public actionresult edit(string id, int? test) { // might need error handling here .... :) var oid = objectid.parse(id); }
you can use tostring
on objectid
convert string calling:
var pid = model.id.tostring();
Comments
Post a Comment