开发者

SelectList Object selectedValue issue

I'm having troubles with the selectedValue option for SelectedItems, for some reason it won't select the item despite it being in the list...

My Controller:

public ActionResult CreateTransformer(string edit)
{    
            var equipment = GenIDQueries.FindEquipment(edit);
            ViewData["Feeder"] = new SelectList(GenIDQueries.GetFeeders(equipment.OpsCentre.ToString()),
                                                "CircuitID",
                                                "CircuitDescription",
                                                equipment.Feeder);
        return View(equipment);
    }

equipment.Feeder is of type Integer.

My View:

<p>
                <b><%=Html.LabelFor(m=>m.Feeder) %>:</b><font color="red">*</font>
                <%=Html.DropDownListFor(m=>m.Feeder, ViewData["Feeder"] as SelectList, "") %>
                <%= Html.ValidationMessageFor(m => m.Feeder)%>
            </p>

My GenIDQueries.GetFeeders:

public static IEnumerable<Circuit> GetFeeders(string distNo)
        {
            int distNoN开发者_运维百科umber;
            if ( int.TryParse(distNo, out distNoNumber))
            {
                return ActiveRecordLinq.AsQueryable<Circuit>()
                .Where(x => x.DistrictCircuitRelations
                          .Any(y => y.District.DistrictNo == distNoNumber))
                .OrderBy(x => x.CircuitDescription)
                .Select(x => new Circuit
                {
                    CircuitID = x.CircuitID,
                    CircuitDescription = x.CircuitDescription
                });
            }
            return new List<Circuit>();
        }

I have verified that the element I wanted to select is indeed returned by GenIDQueries, however when the page loads it never selects that option, in the HTML source code, the item is not selected either.

Thanks for the help!


When setting the selected value you should set it to the selected CircuitID and not the Feeder object.


Why are you using this Plague of ViewData? I consider ViewData as a virus started at Microsoft open space laboratories and spread through internet blog posts and articles.

View models are the way to go in ASP.NET MVC:

Model:

public class MyViewModel
{
    public string SelectedValue { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

Controller:

public ActionResult CreateTransformer(string edit)
{    
    var equipment = GenIDQueries.FindEquipment(edit);
    var items = GenIDQueries.GetFeeders(equipment.OpsCentre.ToString());
    var model = new MyViewModel
    {
        SelectedValue = equipement.CircuitID,
        Items = new SelectList(items, "CircuitID", "CircuitDescription")
    };
    return View(model);
}

View:

<%= Html.DropDownListFor(m => m.CircuitID, Model.Items, "") %>
<%= Html.ValidationMessageFor(m => m.CircuitID) %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜