Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to MVC, please help me to set the selected value in drop down list populated using View Data ,
I have gone through so many solutions but every solutions deals with selecting value for single drop down.I have same drop down listed using the foreach loop. Setting selected value for each dropdown in that foreach loop.
my code is shown below...

[In view]

HTML
 int i = 0;

foreach (var item in Model.Select((x, j) => new { Data = x, Index = j + 1 }))
{
  @Html.DropDownListFor(model => item.Data.CategoryID,IEnumerable<SelectListItem>)ViewData["categories"], new { @id = "category" + i })
i++;
  }

[in controller]
HTML
SelectList selectList = new SelectList((IEnumerable<Category>)ConvertCategoryToList(dt1), "CategoryID", "CategoryName");
           ViewData["categories"] = selectList;
Posted
Updated 24-Apr-14 21:18pm
v2
Comments
NKHari 25-Apr-14 2:50am    
i am having 5 model items so it will list 5 dropdown for category with different categoryId , and I have to get the selected value for the 5 dropdown list as the corresponding categoryId ie,(item.Data.CategoryId)

Please help me ...

I got the solution.....
Thanks for the response everyone.

@Html.DropDownListFor(model => item.Data.CategoryID, new SelectList((IEnumerable<mvcworkstatusmanager.models.category>)ViewData["categories"], "CategoryID", "CategoryName", item.Data.CategoryID),"-Select Category-", new { @id = "category" + i })

Declaring select list in the view page give me the solution.
This code gives me the right selected category corresponding to each item.data from the database.
 
Share this answer
 
SelectList selectList = new SelectList((IEnumerable<category>)ConvertCategoryToList(dt1), "CategoryID", "CategoryName",1);
            ViewData["categories"] = selectList;

</category>

You have written correctly only need to mention which id you need to select default. Where I have mention manually 1 new "CateogryName"

You need to check it dynamically
 
Share this answer
 
Comments
NKHari 25-Apr-14 4:39am    
Thanks for the response but i have a list of drop down so while I give a value or object like that you referred i will get only the same selected value for all the drop down.
My doubt is all about how to get corresponding selected values by passing the object as selectedValue from the controller or by using model (item.Data.CategoryID) in the view page ,which will provide the drop down list in the foreachloop corresponding selected value.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900