MVC:如何在视图中为两个diff dropdownList使用相同的选定项

时间:2014-09-04 19:21:52

标签: asp.net-mvc

我在两个差异下拉列表中使用相同的选定项目。以下是视图代码。

<div id="divSelectingItem1" class="editor-field">
  @Html.LabelFor(m => m.LocationOne)
  @(Html.Kendo().DropDownListFor(m => m.SelectedLocation)
      .DataTextField("Text").DataValueField("Value")
      .BindTo(Model.LocationOne)
      .Value(Model.SelectedLocation))         
</div>


<div id="divSelectingItem2" class="editor-field">
  @Html.LabelFor(m => m.LocationTwo)
  <span id="spnObsDateTimeIcon" class="k-icon k-i-note"></span>
  @(Html.Kendo().DropDownListFor(m => m.SelectedLocation)
      .DataTextField("Text").DataValueField("Value")
      .BindTo(Model.LocationTwo)
      .Value(Model.SelectedLocation))
</div>

模型类

public class LocationViewModel :ViewModelBase
{
    [DisplayName("Identifier Location")]
    public List<SelectListItem> LocationOne{ get; set; }
    public string SelectedLocation{ get; set; }

    [DisplayName("Identifier Location")]
    public List<SelectListItem> LocationTwo{ get; set; }

}

但是上面的代码不起作用..我犯了什么错误?我是.net MVC的新手任何帮助...

1 个答案:

答案 0 :(得分:0)

为了使绑定正常工作,我认为您必须为下拉元素指定与应该绑定的模型属性相同的名称。

<div id="divSelectingItem1" class="editor-field">
  @Html.LabelFor(m => m.LocationOne)
  @(Html.Kendo().DropDownListFor(m => m.SelectedLocation)
      .Name("SelectedLocation") //<--Name of the model property 
      .DataTextField("Text").DataValueField("Value")
      .BindTo(Model.LocationOne)
      .Value(Model.SelectedLocation))         
</div>

我不认为您可以使用绑定模型方法来表示相同属性的两个元素。我想如果你尝试过会遇到js错误。如果变量确实让它返回到你的控制器那么我敢打赌SelectedLocation将是第一个下拉列表的值。

解决此问题的一种方法是给下拉列表一个唯一的名称,然后在准备好发送数据时保存它们。但是你仍然需要两个属性。

听起来你想要一个默认值,在这种情况下,如下所示:

<div id="divSelectingItem1" class="editor-field">
  @Html.LabelFor(m => m.LocationOne)
  @(Html.Kendo().DropDownListFor(m => m.SelectedLocationOne)
      .Name("SelectedLocationOne") //<--Name of the model property 
      .DataTextField("Text").DataValueField("Value")
      .BindTo(Model.LocationOne)
      .Value(Model.DefaultSelectedLocation))         
</div>



<div id="divSelectingItem2" class="editor-field">
  @Html.LabelFor(m => m.LocationTwo)
  <span id="spnObsDateTimeIcon" class="k-icon k-i-note"></span>
  @(Html.Kendo().DropDownListFor(m => m.SelectedLocationTwo)
      .Name("SelectedLocationTwo")
      .DataTextField("Text").DataValueField("Value")
      .BindTo(Model.LocationTwo)
      .Value(Model.DefaultSelectedLocation))
</div>