質問

I got two ways to bind my list of values to a dropdown in MVC3. But not sure which is the difference and the best/simpler way to bind.

//Code

public List<SelectListItem> CountryList
        {
            get
            {
                return new List<SelectListItem>
            {
                new SelectListItem { Value = "1", Text = "Bangladesh" },
                new SelectListItem { Value = "2", Text = "India" },
                new SelectListItem { Value = "3", Text = "Nepal" },
                new SelectListItem { Value = "4", Text = "SriLanka" },
            };
            }
        }

(Or)

public SelectList StatusList()
        {

            List<SelectListItem> lstStatus = new List<SelectListItem>
                {
                    new SelectListItem { Value = "1", Text = "Yes" },
                    new SelectListItem { Value = "2", Text = "No" },
                };

            return new SelectList(lstStatus, "Value", "Text", Status);


        }

Do i have any advantages/disadvantages in one over another. I have to bind these values and get/set the selected value. Which method will be best one go with?

Kindly suggest.

役に立ちましたか?

解決

I tend to use a generic enumeration of SelectListItem in MVC applications. The main reason is that makes more sense when you use ViewModels with your views.

Let's say I have movies stored in a database. I represent a movie with a POCO class.

public class Movie
{
    public string Genre { get; set; }
}

The page to edit the movie receive a ViewModel.

public class MovieViewModel
{
    public string Genre { get; set; }

    public IEnumerable<SelectListItem> GenreList
    {
        get
        {
            yield return new SelectListItem { Text = "Comedy", Value = "1" };
            yield return new SelectListItem { Text = "Drama", Value = "2" };
            yield return new SelectListItem { Text = "Documentary", Value = "3" };
        }
    }
}

The ViewModel is my model but with additional properties to personalize my view, like the list of the available genres.

Finally in my view, I populate my dropdownlist using the ASP.NET wrapper Html.DropDownListFor().

@model MvcApplication1.Models.MovieViewModel

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
        @Html.DropDownListFor(m => m.Genre, Model.GenreList)
    </div>
</body>
</html>

The selected value is then automatically chosen using the ViewModel.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top