c# - Is it possible to redirect to another action passing it as well our current Model as HttpPost? -
so, experimenting asp.net mvc , have following code:
public class trollcontroller : controller { public actionresult index() { var trollmodel = new trollmodel() { name = "default troll", age = "666" }; return view(trollmodel); } [httppost] public actionresult index(trollmodel trollmodel) { return view(trollmodel); } public actionresult createnew() { return view(); } [httppost] public actionresult createnew(trollmodel trollmodel) { return redirecttoaction("index"); } }
the idea have index page shows age of our troll name.
there's action allows create troll, , after creating should index page time our data, instead of default one.
is there way pass trollmodel
createnew(trollmodel trollmodel)
receiving index(trollmodel trollmodel)
? if yes, how?
the best approach persist troll somewhere on server (database?) , pass id index action when redirecting can fetch back. possibility use tempdata or session:
[httppost] public actionresult createnew(trollmodel trollmodel) { tempdata["troll"] = trollmodel; return redirecttoaction("index"); } public actionresult index() { var trollmodel = tempdata["troll"] trollmodel; if (trollmodel == null) { trollmodel = new trollmodel { name = "default troll", age = "666" }; } return view(trollmodel); }
tempdata survive single redirect , automatically evicted on subsequent request whereas session persistent across http requests session.
yet possibility consists passing properties of troll object query string arguments when redirecting:
[httppost] public actionresult createnew(trollmodel trollmodel) { return redirecttoaction("index", new { age = trollmodel.age, name = trollmodel.name }); } public actionresult index(trollmodel trollmodel) { if (trollmodel == null) { trollmodel = new trollmodel { name = "default troll", age = "666" }; } return view(trollmodel); }
now might need rename index post action cannot have 2 methods same name , arguments:
[httppost] [actionname("index")] public actionresult handleatroll(trollmodel trollmodel) { return view(trollmodel); }
Comments
Post a Comment