简体   繁体   中英

How to display selected dropdown item in View of an MVC application

I have a dropdown list selection in one view that I want to display in a different view. The dropdown options are stored in a List variable of type 'SelectListItem' called 'options'.

This is the view I want to display it in. The options index cannot take a lambda expression as I've currently tried it. How do I index the List properly in the view to display the string that's been chosen by the user?

@model SolutionName.Models.ClassType


@{
 Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<p>ID: @Html.DisplayFor(x => x.ID)  </p>
<p>Name:  @Html.DisplayFor(x => x.options[x => x.ID])</p>
</head>

Hi This is my solution , if i have understood your problem correctly

your question:

How do I index the List properly in the view to display the string that's been chosen by the user?

Here you refer indexing the list property ,that means you want to display the dropdown list in this view with the selected value of user, in the previous view. Correct me if am wrong.

If that is the case, you can set the selected property of the select list item and get the value whatever you want.

Ex:

List<SelectListItem> mlist = new List<SelectListItem>();
           mlist.Add(new SelectListItem { Text = "-Please select Option-", Value = "Select" });
           mlist.Add(new SelectListItem { Text = "No", Value = "No", Selected = true});
           mlist.Add(new SelectListItem { Text = "Yes", Value = "Yes" });

additional info: https://stackoverflow.com/a/9806456/3397630

Hope it helps

Thanks Karthik

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM