2013-10-29 58 views
0

我正在使用ASP MVC 3,并且当我更改我的dropdownlistfor的值时,当前有问题在我的文本框中获取新数据。更改TextBoxFor当更改DropDownListFor

<div id="BagelProductEdit"> 
      <h2>Bagel</h2> 
      @Html.DropDownListFor(x => x.SelectedOptionBagel, Model.LstBagelsList, new { @class = "width200", @onchange = "refreshTextBoxFors()" }) 
      <br /> 

       <table> 
       <tr> 
        <td>Bagelnaam</td><td> @Html.TextBoxFor(x => x.LstBagels.ElementAt(x.SelectedOptionBagel).Name,new { Name ="txtEditBagelName" })</td> 
       </tr> 
       <tr> 
        <td>Vertaling</td><td> @Html.TextBoxFor(x => x.LstBagels.ElementAt(x.SelectedOptionBagel).NameFr,new { Name ="txtEditBagelNameFr" })</td> 
       </tr> 
       <tr> 
        <td>Prijs</td> 
        <td> @Html.TextBoxFor(x => x.LstBagels.ElementAt(x.SelectedOptionBagel).Price,new { Name ="txtEditBagelPrice" })</td> 
       </tr> 

      </table> 
      <input class="button widthorderProduct" type="submit" name="BtnEditBagel" value="Edit een bagel" /> 
     </div> 

当我的下拉列表的值发生变化时,如何在我的文本框中获取刷新值?

回答

0

您可以添加一个ID到下拉列表:

@Html.DropDownListFor(x => x.SelectedOptionBagel, Model.LstBagelsList, new { @class = "width200", @onchange = "refreshTextBoxFors()", id= "myDDL" }) 

然后,在refreshTextBoxFors()你可以访问下拉列表中选择值这样(假设你使用jQuery的):

$("#myDDL").val(); 

如果您需要选择的文字(不是数值):

$("#myDDL :selected").text(); 

在你不使用jQuery的,但普通的Javascript,你可以用这个在DropDownList中获取选择的值:

var e = document.getElementById("myDDL"); 
var selValue = e.options[e.selectedIndex].value; 

编辑 - 设置文本框的数据:

一旦你的DDL选择的值,你可以这样做:现在

if(selValue == '1'){ 
    $('#test').val('here is the value you want to put'); 
} 
else{ 
$('#test').val('other value'); 
} 

,在您的评论的例子,看来你有tex的列表tBoxFors。所以如果你在一个循环中添加一个id,它会将它设置到所有的文本框中。您可以改为@class = "test",然后使用$('.test')而不是$('#test')访问文本框。

+0

这是一个很好的例子,如何检索索引,但仍textboxfors没有更新.. 我现在有一个功能,从下拉列表retreive指数: 功能refreshTextBoxFors(){ $(“#bagelname” ).VAL($( “#myDDL”)VAL())。 index = $(“#bagelname”)。val(); } 这是我textboxfor: ​​Bagelnaam​​@ Html.TextBoxFor(X => x.LstBagels.ElementAt(指数).name和新{名称= “txtEditBagelName” ID = “测试”}) –