Alex
Alex

Reputation: 1061

ASP .NET MVC 3 DropDownListFor problem

In the Model, I have:

public Guid? Country
{ get; set; }

In the View, I have:

@Html.DropDownListFor(m => m.Country, (SelectList)ViewBag.Countries)

When submitting, error occures, cause it wants to save the string to the Guid. How to save the value rather then the text of the drop down list?

Upvotes: 2

Views: 1004

Answers (1)

Alex
Alex

Reputation: 1061

Ok. Got it working with a little bit of a different approach.

Model:

public UserRegistrationModel()
{
    this.InitializeCountries();
}

private void InitializeCountries()
{
    FarmerEntities fe = new FarmerEntities();
    var query = from c in new FarmerEntities().Countries select new { ID = c.ID_Country, Name = c.ISO_Code };
    var countries = query.ToSelectList(c => c.ID.ToString(), c => c.Name);

    this.Countries = countries;
}

public Guid? { get; set; }

public IEnumerable<SelectListItem> Countries
{ get; set; }

Controller:

UserRegistrationModel model = new UserRegistrationModel();

return View(model);

View:

@Html.DropDownListFor(m => m.Country, Model.Countries, "")

Also, you need to implement this extension

public static class EnumerableExtensions
{
    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector)
    {
        return items.ToSelectList(valueSelector, nameSelector, x => false);
    }

    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector, IEnumerable<TValue> selectedItems)
    {
        return items.ToSelectList(valueSelector, nameSelector, x => selectedItems != null && selectedItems.Contains(valueSelector(x)));
    }

    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector, Func<TItem, bool> selectedValueSelector)
    {
        foreach (var item in items)
        {
            var value = valueSelector(item);

            yield return new SelectListItem
            {
                Text = nameSelector(item),
                Value = value.ToString(),
                Selected = selectedValueSelector(item)
            };
        }
    }
}

Upvotes: 2

Related Questions