I am working on a website that allows people to register for events. On the registration page, I have a form that captures the data, validates in an MVC controller, persists it between Views, and then is supposed to display a preview page.
Below is a simplified example of what I am trying to do.
Person ViewModel
public class Person{
public int TitleId {get; set;}
public SelectList Titles {get; set;}
}
Register Controller
public class RegisterController:Controller
{
[HttpGet]
public ActionResult Register(){
return View(new Person());
}
[HttpPost]
public ActionResult Register(Person person){
if(ModelState.IsValid){
TempData["Person"] = person
RepopulateSelectLists(); //Gets the data for the select list again
return RedirectToAction("Preview");
}
return View();
}
[HttpGet]
public Actionresult Preview(){
Person person = (Person)TempData["Person"];
}
}
Preview View
@Html.DisplayFor(m => m.TitleId); //Will display int, not selected value
Assuming my SelectList has all of the values, and I have the key/Id of the value selected on the previous page, how do I redisplay just the text of what they selected?
It doesn’t work that way. In your Preview() page you’d take the given ID and find its associated name. You’ll likely want to build a custom View Model (VM) in this case to keep the ID and the Name in the VM.
Also, the moment you hit F5 on the preview page, everything will be GONE. TempData doesn’t persist and any refreshing of the page will lose the data.
I would recommend, instead, that on successful postback, you just return a different view based on the initial post data. For example:
An example VM of a person
Assuming GetTitle does a lookup based on the TitleID. It’s very coarse code, but I hope you get the gist of it. THen you’d use
Html.DisplayFor(m => m.Title);And if your preview has a post to the next page, you’d want to haveHtml.HiddenFor(m => m.TitleId)to make sure the value passes on but you’d have to do that even with your current method. Alternatively you could store the Title in theViewBag(orViewData -- same thing) and simply not useDisplayForto display the value and pass in the value from theViewBag`Notice I scrapped the
"Preview"method completely. That way, if you hit F5 at this point, it just re-posts with the same data you used to get to the preview page. And assuming you’re not saving (I don’t see where you are) then there’s no harm in posting back. Make sense?