SelectList RRS feed

  • Question

  • User1608082067 posted


    On a view I am displaying a list of categories using a DropDownList:

    <%= Html.DropDownList(null, "Categories") %>  

    On my controller I am using an object as ViewData named PostViewData which includes:

    • Post: an object with the properties PostID, Title, Body and Category
    • Categories: a SelectList with all categories;

    So on Create action of my controller I do the following:    

    private PostViewData viewData = new PostViewData();
    viewData.Targets = new SelectList(GetCategories(), "Value", "Key");

    On my Edit view I do the following:

    PostPaper paper = (from p in database.Posts
                       where s.PostID == id
                       select new PostPaper {
                         Post = p
    string category = GetCategories().Where(c => c.Value == paper.Post.Category).FirstOrDefault().Key;
    viewData.Categories = new SelectList(GetCategories(), "Value", "Key", target ?? "");
    So now I have the DropDownList with the Post Category selected.
    Now the problem. On my Insert view I have:  
    1    PostPaper paper = new PostPaper();
    2    UpdateModel(paper.Post, new[] { "Title", "Body" });
    4    SelectList categories;
    5    UpdateModel(categories, new[] { "Categories" });
    7    paper.Post.Category = categories.SelectedValue.ToString(); 
    Use of unassigned local variable 'categories' on line 5.
    This is because I am not able to do something like?
    SelectList categories = new SelectList();
    SelectList categories = new SelectList.Empty();
    Anyway, I just feel that I am doing something wrong on the way I am filling my DropDownList.
    I need to agree that the previous Html.Select seemed to have more sense as someone suggested in 
    Anyway, what should I do?
    Thursday, September 18, 2008 12:42 PM

All replies

  • User1608082067 posted

    Please, anyone?

    Thank You,


    Tuesday, September 23, 2008 8:41 PM