Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdownlist using viewbag data in mvc4 using c#

Hi i want to fill a dropdown list in my view page my code is

public class MemberBasicData
{
    public int Id { get; set; }
    public string Mem_NA { get; set; }
    public string Mem_Occ { get; set; }
}

//controller

  public ActionResult Register()
    {
        var users = new Member().GetAllMembers();
        ViewBag.Users = users;   
        return View();
    }

//View

 @model IEnumerable<....Members.Models.MemberBasicData>
 @Html.DropDownListFor(model => model.Mem_Na, (SelectList)ViewBag.Users, "--Select Users--")

i want to add Mem_NA to dropdownlist, Viewbag contains all the user details. Problem is in View page. An error shows in model.Mem_Na. Please help me to solve this.

like image 712
neel Avatar asked Jan 12 '23 13:01

neel


2 Answers

Please, change your code

from

@model IEnumerable<....Members.Models.MemberBasicData>
@Html.DropDownListFor(model => model.Mem_Na, (SelectList)ViewBag.Users, "--Select Users--")

to

@model ....Members.Models.MemberBasicData
@Html.DropDownListFor(model => model.Id,new SelectList(ViewBag.Users,"Id","Mem_NA"), "--Select Users--")

It works for me everytime

like image 77
Elvin Mammadov Avatar answered Jan 22 '23 02:01

Elvin Mammadov


Your model is an IEnumerable of MemberBasicData, not an instance of MemberBasicData. This means you cannot access properties of MemberBasicData directly, as the property doesn't exist against an IEnumerable.

From what little I can see from your code I imagine you want your model to be an instance, not a list.

like image 33
Ryan Amies Avatar answered Jan 22 '23 01:01

Ryan Amies