views:

68

answers:

1

I am confused about making DropdownList in MVC. let's start with a simple case. In Address view I have a textbox for City, and a dropdown for State. My model Address table made by Linq to SQL has the following properties:

Public string City{get;set;}
Public string State{get;set;}

and another table with states. in my controller i made the following method:

public static SelectList getLang(string index)
{

       using (namespace.DB db = new namespace.DB())
         {
            List<namespace.Model.tbl_State> state= (from S in db.tbl_State orderby   L.Name select L).ToList();
            SelectList sel = new SelectList(state, "ID", "Name", index);
            return sel;
        }
    }

and actionresult for edit is like:

    public ActionResult Edit(int id)
    {
        using (namespace.DB db = new namespace.DB())
        {
            namespace.Model.tbl_Address add= db.tbl_Address.Single(T => T.ID == id);

            return View(add);
        }
    }

Now how to put all those method together. I'd like in my view showing the city and the state in its dropdown list with CA id as selected. Any help would be greatly appreciated.

A: 

First I would start with reading some tutorials or books about MVC:

http://stackoverflow.com/questions/240905/best-asp-net-mvc-book

You should create view model (read about view models first), which could look like:

class AddressEditModel
{  
    tbl_Address Address;
    List<tbl_State> States;
}

Then you have to construct this model from Linq to SQL:

public AddressEditModel ConstructAddressEditModel(int addressId)
{
    var model = new AddressEditModel();
    using (namespace.DB db = new namespace.DB())
    {
         model.States = state= (from S in db.tbl_State orderby L.Name select s).ToList();
         model.Address = db.tbl_Address.Single(T => T.ID == addressId);
    }
}

Then your edit method:

public ActionResult Edit(int id)
{
    var model = ConstructAddressEditModel(id);
    return View(model);
}

Then declare your view as:

System.Web.Mvc.ViewPage<AddressEditModel>

and use Html.DropDown in your view using Model.States.

LukLed