开发者

MVC populating dropdown in Edit Action

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 getL开发者_高级运维ang(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:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜