开发者

MVC2 SelectedListItem not binding to ViewModel

开发者 https://www.devze.com 2023-02-11 23:08 出处:网络
I am having a problem with a selectlistitem, the values of which are being retrieved from a database.

I am having a problem with a selectlistitem, the values of which are being retrieved from a database.

It is displaying the list of items in the view, but it is not passing through (POSTing) the selected value into the mo开发者_JS百科del.

So when the user submits, or the page reloads due to validation, the select value (PositionApplied) is empty.

Can anyone give me some pointers as to where I am going wrong?

In my controller:

    [HttpGet]
    public ActionResult Index()
    {
        PopulateJobsDropdown();
        return View();
    }

    private void PopulateJobsDropdown()
    {
        IEnumerable<SelectListItem> items = _service.GetJobs()
            .Select(c => new SelectListItem
                             {
                                 Value = c.JobID.ToString(),
                                 Text = c.JobTitle
                             });
        ViewData["PositionApplied"] = items;
    }

In my ViewModel

 public IEnumerable<SelectListItem> PositionApplied { get; set; }

In my View

<%=Html.DropDownList("PositionApplied")%>

Thanks in advance for any pointers!


So, where is the code line that get's the

ViewData["PositionApplied"] = items;

into

public IEnumerable<SelectListItem> PositionApplied { get; set; }

something like:

this.PositionApplied = ViewData["PositionApplied"] as IEnumerable<SelectListItem>;

and you can simple use in your View:

<%
    IEnumerable<SelectListItem> PositionApplied = 
          ViewData["PositionApplied"] as IEnumerable<SelectListItem>;
%>

...

<%= Html.DropDownList("myDropDOwnId", PositionApplied) %>

or is there some of automagical happening under MVC2 that I'm not aware about? As I use the example I give you, all the time.


Added

in order to avoid Linq to Entities error (if you are using it) change your method to

private void PopulateJobsDropdown()
{
    IQueryble<Your_Table> jobs = _service.GetJobs();
    List<SelectListItem> items = new List<SelectListItem>();
    foreach(var job in jobs)
        items.add(new SelectListItem
                      {
                         Value = c.JobID.ToString(),
                         Text = c.JobTitle
                      });
    ViewData["PositionApplied"] = items;
}

and all will work fine.

0

精彩评论

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

关注公众号