我怎样才能干净地包括一个"其他" MVC中的单选按钮列表中的文本框?

时间:2014-05-28 11:34:19

标签: asp.net asp.net-mvc razor

我目前有一个带有“其他”选项的单选按钮列表。

@Html.RadioButtonFor(model => model.Language, "English") English
@Html.RadioButtonFor(model => model.Language, "Spanish") Spanish
@Html.RadioButtonFor(model => model.Language, "Other") Other:
@Html.TextBoxFor(model => model.OtherLanguage)

但是,此设置需要模型中的其他字段。例如,如果用户单击“其他”并键入“法语”,则模型将包含:

Language: Other
OtherLanguage: French

我想要一个更简洁的方法,其中模型只包含Language: French。最简单的方法是什么?

1 个答案:

答案 0 :(得分:1)

使用Jquery

@Html.TextBoxFor(m => m.Language) // assume this renders id="Language"

然后创建单选按钮(不使用HtmlHelpers)

<input type="radio" name="language" value="English" /> // plus label
<input type="radio" name="language" value="Spanish" /> // plus label
....

在剧本中

$('input[type="radio"]').change(function () { // or input[name="language"]
  $('#Language').val($(this).val());
}