如何显示与视图模型绑定时选择的下拉数据

时间:2016-01-05 18:13:44

标签: asp.net-mvc razor

小提琴:https://dotnetfiddle.net/BrKBx1

模型

public class StatesVm 
{
    public int SelectedStateId { get; set; }
    public List<State> States { get; set; }
}

public class State {
    public int ID { get; set; }
    public string Name { get; set; }
}

控制器

public ActionResult DropDownListForDemo()
{
    StatesVm vm = new StatesVm() { SelectedStateId = 2 };
    List<State> states = new List<State>();
    states.Add(new State() { ID = 1, Name = "West Bengal" });
    states.Add(new State() { ID = 2, Name = "Bihar" });
    states.Add(new State() { ID = 3, Name = "Orissa" });
    vm.States = states;

    return View(vm);
}

视图

@model CsMvcDemo.Models.StatesVm
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>DropDownListForDemo</title>
</head>
<body>
    <div>
        @Html.DropDownListFor(x => x.SelectedStateId, new SelectList(Model.States, "ID", "Name",2), "-- Select States--", new { id = "cboState" })
    </div>
</body>
</html>



@Html.DropDownListFor(x => x.SelectedStateId, new SelectList(Model.States, "ID", "Name",3), "-- Select States--", new { id = "cboState" }) 

我想显示根据我的传递值选择的下拉值。当我将值设置为1或3并运行代码时,应更改状态名称,但它显示的是旧名称。

1 个答案:

答案 0 :(得分:0)

使用Get-AzureRmResourceGroup时,必须先将模型中的选定项目设置为视图。如果您想对所选项目进行硬编码,请使用DropDownListFor

使用DropDownListFor

将您的模型更改为

DropDownList

将控制器更改为

public class StatesVm 
{
    public int SelectedStateId { get; set; }
    public IEnumerable<SelectListItem> States
    {
        get
        {
            yield return new SelectListItem { Text = "West Bengal", Value = "1" };
            yield return new SelectListItem { Text = "Bihar", Value = "2" };
            yield return new SelectListItem { Text = "Orissa", Value = "3" };
        }
    }
}

您的观点

public ActionResult DropDownListForDemo()
{
    var viewModel = new StateVm
        {
            SelectedStateId= 2
        };

        return View(viewModel);
}

DropDownListFor期望模型值( @Html.DropDownListFor(m => m.SelectedStateId, Model.States) )在下拉列表中设置所选项。使用x=>x.SelectedStateId设置所选项目将被忽略,并将使用SelectedStateId。

要在视图中对所选值进行硬编码,您可以使用DropDownList而不是DropDownListFor。

使用DropDownList

SelectList(Model.States, "Value", "Text", "2")