views:

249

answers:

3

Hello All,

I am having a dropdownlist in my appliaction which I have binded through the database records but on any of the edit form I want to set the selected index of the dropdown list how shall I do that ,I am Pastng my code here.

Code for binding the dropdownlist

public IList GetFeedbackList()
{
  int feedbackId = 0;
  string feedbackName = string.Empty;

  using (var db = new brandconnectionsEntities())
  {
    return (IList )(from s in db.BC_FeedbackBy
                      select new
                      {

                         feedbackId =s.FeedbackById ,
                         feedbackName=s.FeedbackBy  ,
                      })
                  .ToList ();
  }
}

//Code for returning the list

IList allfeedbacks = _dropdownProvider.GetFeedbackList();

ViewData["feedback_for"] = new SelectList(allfeedbacks, "feedbackId", "feedbackName");

//In the View Page
<%=Html.DropDownList("feedback_for", ViewData["feedback_for"] as SelectList, "--Select--", new { @class = "inputtext1" })%>

Please tell how shall I set the selected index from database

Thanks Ritz

A: 
ViewData["feedback_for"] = new SelectList(allfeedbacks, "feedbackId", "feedbackName", selectedvalue);

At least in MVC2.

I had a problem though wich disappeared when i gave the dropdown the same name as the key. Ie:

<%=Html.DropDownList("feedbackId", ViewData["feedback_for"] as SelectList, "--Select--", new { @class = "inputtext1" })%>
magnus
A: 

In the constructor for your select list you can specify the selected item....

ViewData["feedback_for"] = new SelectList(allfeedbacks, "feedbackId", "feedbackName", 
                allfeedbacks.FirstOrDefault(f => f.FeedbackById == {ID of selected record})); 
MarkB29
A: 

Pass a List of SelectListItems to the View. SelectListItem has a property selected.

 IEnumerable<SelectListItem> itemList =
                from item in Items
                select new SelectListItem
                {
                    Text = item.Name,
                    Value = item.Key,
                    Selected = ( item.Key == "TheKeyYouWantToSet")
                };
Malcolm Frexner