开发者

Radio button using Html.RadioButtonFor runs server code when clicked

How can I use Html.RadioButtonFor to create radio button which when clicked runs code on the server and controls visibility of certain text box. earl开发者_如何学JAVAier I used to create <asp:control with autopostback="true" Thanks


As always you could start by creating a view model:

public class MyViewModel
{
    public int RadioValue { get; set; }
}

then a controller:

[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);
    }
}

and finally a strongly typed view:

<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" />


I'm not entirely sure what you mean but to make a regular radio-button do a postback you need to use javascript (jquery is what i would've used) which performs a postback for you (remember to make sure your telling it to do a real postback and not an async postback).

Make sure you point the postback to a actionresult which does what you want with the viewmodel to reflect the selected option and send it to the view again, the view would then contain lighter code like if,else or whatever you need to reflect the choices made by the user.

Edit:

$(".rbClass").Click(function(){
    $("formToSubmit").submit();
});

this should work for a regular postback, you should look into ajax, there's even an option to set the property "async:false" when using $.ajax() check jquery or search here and you'll get great examples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜