Reputation: 1265
Hi guys how can one get selected value?
Here is my model
public class PaymentModels
{
public int CreditCardNumber { get; set; }
public List<SelectListItem> CardType { get; set; }
public static List<SelectListItem> getCardTypes()
{
List<SelectListItem> cardType = new List<SelectListItem>();
cardType.Add(new SelectListItem { Text = "American Express"});
cardType.Add(new SelectListItem { Text = "Mastercard" });
cardType.Add(new SelectListItem { Text = "Visa" });
return cardType;
}
}
This is how the list is shown on view via controller
ViewData["List"] = PaymentModels.getCardTypes();
And here is my post back method
[HttpPost]
public ActionResult Payment(PaymentModels pay)
{
String vr;
foreach(var v in pay.CardType) {
vr= v.Selected.ToString();
}
return View();
}
My question is that how can i get the selected value from my cardtype list when post event is invoked?
Upvotes: 2
Views: 801
Reputation: 1038790
You need to add values to your items, not only text:
public static List<SelectListItem> getCardTypes()
{
List<SelectListItem> cardType = new List<SelectListItem>();
cardType.Add(new SelectListItem { Value = "1", Text = "American Express" });
cardType.Add(new SelectListItem { Value = "2", Text = "Mastercard" });
cardType.Add(new SelectListItem { Value = "3", Text = "Visa" });
return cardType;
}
Now you could simply add a property on your view model:
public int SelectedCardType { get; set; }
And in the view:
<%= Html.DropDownListFor(
x => x.SelectedCardType,
(IEnumerable<SelectListItem>)ViewData["list"]
) %>
and in your controller action:
[HttpPost]
public ActionResult Payment(PaymentModels pay)
{
// pay.SelectedCardType will contain the selected value (1, 2 or 3)
...
}
Of course the values should not necessary be integers. You could use a string property as well:
public static List<SelectListItem> getCardTypes()
{
List<SelectListItem> cardType = new List<SelectListItem>();
cardType.Add(new SelectListItem { Value = "American Express", Text = "American Express" });
cardType.Add(new SelectListItem { Value = "Mastercard", Text = "Mastercard" });
cardType.Add(new SelectListItem { Value = "Visa", Text = "Visa" });
return cardType;
}
and:
public string SelectedCardType { get; set; }
Upvotes: 5