【发布时间】:2010-10-18 17:43:46
【问题描述】:
如何使用Html.RadioButtonFor 创建单选按钮,单击该按钮可在服务器上运行代码并控制某些文本框的可见性。之前我用autopostback="true" 创建<asp:control 谢谢
【问题讨论】:
标签: .net asp.net asp.net-mvc webforms radiobuttonfor
如何使用Html.RadioButtonFor 创建单选按钮,单击该按钮可在服务器上运行代码并控制某些文本框的可见性。之前我用autopostback="true" 创建<asp:control 谢谢
【问题讨论】:
标签: .net asp.net asp.net-mvc webforms radiobuttonfor
与往常一样,您可以从创建视图模型开始:
public class MyViewModel
{
public int RadioValue { get; set; }
}
然后是控制器:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
// Set to some initial value
RadioValue = 1
});
}
public ActionResult CheckVisibility(int radioValue)
{
return Json(new
{
// based on the value of the radio decide whether
// the textbox should be shown
visible = radioValue == 1
}, JsonRequestBehavior.AllowGet);
}
}
最后是强类型视图:
<script type="text/javascript">
$(function () {
// when one of the two radio buttons is clicked
$('.myradio').click(function () {
// prepare the request
var data = { radioValue: $(this).val() };
// url to send the AJAX request to
var url = '<%= Url.Action("checkvisibility") %>';
// send an AJAX request
$.getJSON(url, data, function (json) {
// when the request succeeds toggle the visibility of the textbox
// based on the JSON response returned by the server
$('#foo').toggle(json.visible);
});
});
});
</script>
Value 1: <%: Html.RadioButtonFor(x => x.RadioValue, "1", new { @class ="myradio" })%>
Value 2: <%: Html.RadioButtonFor(x => x.RadioValue, "2", new { @class = "myradio" })%>
<br/>
<input type="text" id="foo" name="foo" value="bar" />
【讨论】:
我不完全确定您的意思,但要使常规单选按钮执行回发,您需要使用 javascript(我会使用 jquery)为您执行回发(请记住确保您的告诉它做一个真正的回发而不是异步回发)。
确保您将回发指向一个 actionresult,该操作结果对视图模型执行您想要的操作以反映所选选项并将其再次发送到视图,然后视图将包含更轻的代码,例如 if、else 或您需要反映的任何内容用户做出的选择。
编辑:
$(".rbClass").Click(function(){
$("formToSubmit").submit();
});
这应该适用于常规回发,您应该查看 ajax,甚至可以选择在使用 $.ajax() 检查 jquery 或在此处搜索时设置属性“async:false”,您会得到很好的示例。
【讨论】: