选择控制器中的下拉项

时间:2016-06-21 09:15:26

标签: c# html asp.net-mvc

美好的一天

在我看来,我有一个如下的下拉列表:

<div class="form-group row">
    @Html.LabelFor(model => model.Colour, new { @class = "col-lg-2 col-md-2 col-sm-2 col-xs-2" })
    <div class="col-lg-9 col-md-9 col-sm-9 col-xs-9">
        @Html.DropDownListFor(model => model.Colour, new SelectList(Model.VehicleColour, "Value", "Text", Model.Colour), new { id = "Colour", @class = "btn dropdown-toggle btn-default" })
    </div>
</div>

已更新。在某种情况下,我需要在控制器中设置所选项目。目前我正试图通过这样做来实现这一目标(但这不起作用):

[HttpPost]
public ActionResult VehicleDetails(VehicleDisplay model)
{
    // This section depends on the condition and it gets the item id that I need
    // to select in the dropdown 
    if (Session["ColourID"] != null)
    {
        model.Colour = long.Parse(Session["ColourID"].ToString());
    }
    #endIf

    model.VehicleColour = GetVehicleColour();
    foreach (SelectListItem colour in model.VehicleColour)
    {
        if (colour.Value == model.Colour.ToString())
        {
            colour.Selected = true;
        }
        else
        {
            colour.Selected = false;
        }
    }
    return PartialView("VehicleDetails", model);
}

GetVehicleColour()

private IEnumerable<SelectListItem> GetVehicleColour()
{
    var colours = new List<SelectListItem>();
    var colour = new SelectListItem()
    {
        Value = "0",
        Text = "Please select a Vehicle Colour",
        Selected = true
    };

    /* Get Colour values fron database */

    foreach (ColorObject method in dbList)
    {
        colour = new SelectListItem()
        {
            Value = method.Id.ToString(),
            Text = method.Description,
            Selected = false
        };
        colours.Add(colour);
    }
    return colours;
}

VehicleModel

[Required]
[Display(Name = "Colour ")]
[Range(1, long.MaxValue, ErrorMessage = "Please select a Vehicle Colour")]
public long? Colour { get; set; }

public IEnumerable<SelectListItem> VehicleColour { get; set; }
你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

你可以这样试试;

在控制器中你应该写;

List<VehicleColour> lstColour = null;
lstColour = GetVehicleColour();
ViewBag.lstColour = new SelectList(lstColour , "Colour", "Colour", selected Colour);

您的观点应如下所示;

 @Html.DropDownList("lstColour", null, new { id = "Colour", @class = "btn dropdown-toggle btn-default" })