如何使用Html.RadioButtonFor创建单选按钮,当单击该按钮时,将在服务器上运行代码并控制某些文本框的可见性。之前我经常用autopostback="true"创建<asp:control,谢谢
发布于 2010-10-19 02:10:17
我不完全明白你的意思,但是要让一个普通的单选按钮做一个回发,你需要使用javascript (jquery是我会用到的),它会为你执行一个回发(记得要确保你告诉它做一个真正的回发,而不是异步回发)。
确保将回发指向一个option _ reflect,该option_ reflect对视图模型执行您想要的操作,以反映所选的选项,并再次将其发送到视图,然后视图将包含更轻量级的代码,如if、else或任何您需要反映用户所做选择的代码。
编辑:
$(".rbClass").Click(function(){
$("formToSubmit").submit();
});这应该适用于常规的回发,你应该看看ajax,甚至有一个在使用$.ajax() check jquery或search here时设置属性"async:false“的选项,你会得到很好的例子。
发布于 2010-10-19 03:51:01
像往常一样,您可以从创建视图模型开始:
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" />https://stackoverflow.com/questions/3961803
复制相似问题