0
@if (ViewBag.language != null)
{
    foreach (var item in ViewBag.language)
    {
        <div class="control-label col-md-2">Language</div>
        <div class="col-md-6">
            @Html.DropDownList("LanguageId", null, new { @class = "form-control" },@item.LanguageID)
        </div>
    }
}

the ViewBag.Langauge contains the LangaugeID and foreach iteration I want to set the dropdownlist selected value as value of @item.langaugeID

ViewBag.LanguageId = new SelectList(db.Languages, "LanguageId", "LanguageName");

Contains all the languages in database

for (int i = 0; i < count; i++)
{
    int languageid = StudentLanuguages[i];
    List<tblStudentLanguageMapping> StudentLan = new List<tblStudentLanguageMapping>();
    StudentLan = (from a in db.tblStudentLanguageMappings 
                  where a.StudentLanguageMappingId == languageid
                  select a).ToList();
    std.AddRange(StudentLan);
}
ViewBag.language = std;
Amal Sebastian
  • 193
  • 3
  • 19
  • 3
    Possible duplicate of [MVC5 Razor html.dropdownlistfor set selected when value is in array](http://stackoverflow.com/questions/37407811/mvc5-razor-html-dropdownlistfor-set-selected-when-value-is-in-array) –  Apr 13 '17 at 05:20
  • Possible duplicate of [Select a default value in dropdownlistfor MVC 4](http://stackoverflow.com/questions/17805265/select-a-default-value-in-dropdownlistfor-mvc-4) – Dylan Slabbinck Apr 13 '17 at 06:26
  • Thank you @StephenMuecke my question was the same and the link was helpful , but i didnt get the output as i expected can you please provide a sample code so that the value in **@item.LangaugeId** can be set selected in the dropdown list – Amal Sebastian Apr 13 '17 at 09:07
  • @DylanSlabbinck thanks for replying but sir, actually my requirement is like I have a loop and for each iteration the dropdown list should be generated and a value should be set selected. I have that value in **@item.LanguageId** what i dont know is how to pass it to the dropdown in the view itself – Amal Sebastian Apr 13 '17 at 09:16
  • @Akuria, You need to read the dupe. You cannot use `@Html.DropDownList("LanguageId", null, ...`. Use `@Html.DropDownListFor() and strongly bind to a model (and that model will contain a collection of objects containing a property to bind to) –  Apr 13 '17 at 10:18
  • i got it by a much lesser effort don't know whether its the right way to do just by including a javascript { } – Amal Sebastian Apr 18 '17 at 12:44

0 Answers0