locked
SelectList RRS feed

  • Question

  • User1608082067 posted

    Hello,

    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
                       }).SingleOrDefault();
    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" });
    3    
    4    SelectList categories;
    5    UpdateModel(categories, new[] { "Categories" });
    6    
    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();
    or   
    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 
    http://forums.asp.net/t/1318112.aspx 
    Anyway, what should I do?
    Thanks,
    Miguel   
     
      
      
    Thursday, September 18, 2008 12:42 PM

All replies

  • User1608082067 posted

    Please, anyone?

    Thank You,

    Miguel

    Tuesday, September 23, 2008 8:41 PM