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.
First I would start with reading some tutorials or books about MVC:
https://stackoverflow.com/questions/240905/best-asp-net-mvc-book
You should create view model (read about view models first), which could look like:
Then you have to construct this model from Linq to SQL:
Then your edit method:
Then declare your view as:
and use
Html.DropDownin your view usingModel.States.