PDA

Click to See Complete Forum and Search --> : VS 2010 [RESOLVED] MVC 3 DropDownListFor problem


gavio
Aug 8th, 2011, 01:27 PM
Hello.

I'm using VS2010, MVC 3, Razor and Entity Framework 4.

I want to have a drop down list with list of all countries from the Countries table. And in my model, I have just a single country id (Guid).

So, in my Model, I have:public Guid? CountryID
{ get; set; }In my Controller, I have:ViewBag.Countries = from e in new MyEntities().Countries select e;And in my View, I have:@Html.DropDownListFor(m => m.CountryID, new SelectList(ViewBag.Countries, "CountryID", "Name"), "")If I choose something or not, i get the "Value cannot be null", on the View line of the code (@Html.DropDown...). What am I doing wrong?

Also, cause I'm totally new to MVC and Entity Framework, is there a better way to achieve this? I'm Googling this for few hours now with no results...

EDIT: I have just seen I've posted in the wrong forum section, so please, redirect this. Sorry.

gep13
Aug 9th, 2011, 12:50 AM
EDIT: I have just seen I've posted in the wrong forum section, so please, redirect this. Sorry.

No problem :)

Moved to the MVC Forums.

Gary

gavio
Aug 9th, 2011, 03:06 AM
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)
};
}
}
}