首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Html.RadioButtonFor的单选按钮在单击时运行服务器代码

问使用Html.RadioButtonFor的单选按钮在单击时运行服务器代码
EN

Stack Overflow用户
提问于 2010-10-19 01:43:47
回答 2查看 1.7K关注 0票数 0

如何使用Html.RadioButtonFor创建单选按钮,当单击该按钮时,将在服务器上运行代码并控制某些文本框的可见性。之前我经常用autopostback="true"创建<asp:control,谢谢

EN

回答 2

Stack Overflow用户

发布于 2010-10-19 02:10:17

我不完全明白你的意思,但是要让一个普通的单选按钮做一个回发,你需要使用javascript (jquery是我会用到的),它会为你执行一个回发(记得要确保你告诉它做一个真正的回发,而不是异步回发)。

确保将回发指向一个option _ reflect,该option_ reflect对视图模型执行您想要的操作,以反映所选的选项,并再次将其发送到视图,然后视图将包含更轻量级的代码,如if、else或任何您需要反映用户所做选择的代码。

编辑:

代码语言:javascript
复制
$(".rbClass").Click(function(){
    $("formToSubmit").submit();
});

这应该适用于常规的回发,你应该看看ajax,甚至有一个在使用$.ajax() check jquery或search here时设置属性"async:false“的选项,你会得到很好的例子。

票数 1
EN

Stack Overflow用户

发布于 2010-10-19 03:51:01

像往常一样,您可以从创建视图模型开始:

代码语言:javascript
复制
public class MyViewModel
{
    public int RadioValue { get; set; }
}

然后是一个控制器:

代码语言:javascript
复制
[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);
    }
}

最后是一个强类型视图:

代码语言:javascript
复制
<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" />
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3961803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档