填充@ Html.DropDownList的文本和值

时间:2015-06-15 22:00:38

标签: jquery html asp.net

我有一个@ Html.DropDownList,我需要根据先前的选择更改它的文本和值。

if ($(data.agt.CoAgentMLSAID != null) == "True") {
$("#SelectedAgent").html("{0}, {1}", data.agt.CoAgentLastName,
data.agt.CoAgentFirstName);
}

我也试过这个:

$document.getElementById("#SelectedAgent").text = ("{0}, {1}", data.agt.CoAgentLastName, data.agt.CoAgentFirstName);

而不是上面的另一个。没工作

我有这个:

@Html.DropDownList("SelectedAgent", this.Model.OfficeAgents, new { @class = "fl-space2", @id ="SelectedAgent" } )

我得到的是默认值,而不是基于上述if语句的名称值。我怎么能改变呢?默认文本位于模型中。

我对jQuery不是很强,所以我认为这很快。提前致谢

1 个答案:

答案 0 :(得分:1)

尝试以下代码: 创建视图模型如下:

public class ViewModel{

  public List<SelectListItem> OfficeAgents {get; set}
  public string SelectedAgent {get; set}

  public MyViewModel(){
      OfficeAgents = new List<SelectListItem>();
      SelectedAgent = "ABC"; //default values go here
  }

}

将此视图模型发送到您的视图:

public ActionResult Index()
{

    ViewModel model = new ViewModel ();

   //do query and set agents data to model.OfficeAgents and set default agent data

    model.SelectedAgent = "Agent1";

    //Pass it to the view 
    return ActionResult( model);
}

在视图中将您的模型设置为下拉列表:

@Html.DropDownList("SelectedAgent", this.Model.OfficeAgents, this.Model.SelectedAgent, new { @class = "fl-space2", @id ="SelectedAgent" } )