Reputation: 105197
So, I am experimenting with ASP.NET MVC and I have the 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 is to have an index page which shows the age of our troll as well as his name.
There's an action that allows us to create a troll, and after creating it we should get back to the index page but this time with our data, instead of the default one.
Is there a way to pass the TrollModel
CreateNew(TrollModel trollModel)
is receiving to Index(TrollModel trollModel)
? If yes, how?
Upvotes: 0
Views: 2437
Reputation: 1039298
The best approach would be to persist the troll somewhere on the server (database?) and then pass only the id to the index action when redirecting so that it can fetch it back. Another possibility is to use TempData or Session:
[HttpPost]
public ActionResult CreateNew(TrollModel trollModel)
{
TempData["troll"] = trollModel;
return RedirectToAction("Index");
}
public ActionResult Index()
{
var trollModel = TempData["troll"] as TrollModel;
if (trollModel == null)
{
trollModel = new TrollModel
{
Name = "Default Troll",
Age = "666"
};
}
return View(trollModel);
}
TempData will survive only a single redirect and be automatically evicted on the subsequent request whereas Session will be persistent across all HTTP requests for the session.
Yet another possibility consists into passing all the properties of the troll object as 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 you might need to rename the Index POST action as you cannot have two methods with the same name and arguments:
[HttpPost]
[ActionName("Index")]
public ActionResult HandleATroll(TrollModel trollModel)
{
return View(trollModel);
}
Upvotes: 7
Reputation: 31260
In CreateNew there must be some kind of persistence e.g. the troll might be saved in database. It must also have some kind of ID. So the Index method can be changed to
public ActionResult Index(string id)
{
TrollModel trollModel;
if (string.IsNullOrEmpty(id))
{
trollModel = new TrollModel()
{
Name = "Default Troll",
Age = "666"
};
}
else
{
trollModel = GetFromPersisted(id);
}
return View(trollModel);
}
and in the CreateNew
[HttpPost]
public ActionResult CreateNew(TrollModel trollModel)
{
return RedirectToAction("Index", new {id = "theNewId"});
}
Upvotes: 0