I cannot figure out how to pass the text from a <SelectListItem> with a DropDownList from one view to another.
I am using the following in a view:
@using (Html.BeginFormAntiForgeryPost())
{
@Html.Hidden("myData", new MvcSerializer().Serialize(Model, SerializationMode.Signed))
...
@Html.DropDownListFor(m => m.MyProperty, new SelectList(Model.MyPropertyList, "Value", "Text"))
...
}
In my ViewModel (MyData), I have:
[Serializable]
public class MyData
{
public int MyProperty{ get; set; }
public IEnumerable<SelectListItem> MyPropertyList{ get; set; }
...
public MyData()
{
var mypropertylist = new List<SelectListItem>() {
new SelectListItem { Text = "(Please select)" },
new SelectListItem { Value = "1", Text="Some text." },
new SelectListItem { Value = "2", Text="Some other text." }
};
this.MyPropertyList = mypropertylist; //Edited
}
}
I am using a wizard and want to pass the data collected in one step to either the confirmation page or an e-mail my code generates.
For example, if I do @Html.EditorFor(m => m.FirstName) in a view, I can pass that input into a confirmation view by doing @Model.FirstName.
I have RadioButtons for which I am able to do the following: @Html.Raw(MyNamespace.ViewModels.MyModel.MyPropertyDictionary.mypropertyDictionary[Model.MyProperty]) to pass the data to my confirmation view. But I am unable to properly create the @Html.Raw (assuming that’s what I’d have to do) for a DropDown.
Thanks!
UPDATE (To add controller code per comment request):
Controller:
private MyData myData;
....
//
// STEP 1:
// AskUs
public ActionResult AskUsDetails(string nextButton)
{
if ((nextButton != null) && ModelState.IsValid)
return RedirectToAction("AskUsSubmitted");
return View("AskUs/Details", myData);
}
//
// STEP 2:
// AskUs/Submitted
public ActionResult AskUsSubmitted()
{
// Todo: Save myData database; render a "Submitted" view
MyMailer.AskUs(myData).Send();
return View("AskUs/Submitted", myData);
}
Things to note:
- There is a serialization part to the controller. I don’t know if its relevant (let me know if it is and I will edit inside the code above).
- Using MvcMailer, so there are 2 other files involved, but again I don’t know if its relevant (it’s the
MyMailer.AskUs(myData).Send();part above).
UPDATE:
If I do @Model.MyPropertyList in the confirmation view, my view shows
System.Collections.Generic.List1[System.Web.Mvc.SelectListItem]
If I use @Model.MyProperty I am getting the value, e.g.,
1
I just need to figure out how to output the actual “Text” contained, for example, in
new SelectListItem { Value = "1", Text="**Some text.**" }
Any examples of how to do that would be much appreciated.
When you submit a form containing a dropdown list, only the selected value is sent to the server. If you wanted to fetch the corresponding text you could use this selected value and search into the corresponding list.
Also you don’t need to manually add the
(Please select)item to your collection. This could be done in the view directly: