简体   繁体   中英

How to get the selected value of a asp.net mvc Html.radiobuttonfor

I've two radio buttons,

<%= Html.RadioButtonFor(m =>m.Type,true,new {id = "rdPageType",CHECKED = "checked" }) %>
<%= Html.RadioButtonFor(m =>m.Type,true,new {id = "rdPageType12",CHECKED = "checked" }) %>

How can I check which is selected, when the 1st is selected, I should be able to set the boolean value of 'rdPageType' to true, and the other as false, vice versa

Help please

Assuming you have the following model:

public class MyModel
{
    public bool RdPageType { get; set; }
}

Your controller might look like this:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // Action to render the form, initialize the model
        // with some default value
        var model = new MyModel
        {
            RdPageType = true
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyModel model)
    {
        // Action called when the form is posted
        // model.RdPageType will depend on the radio
        // being selected
        return View(model);
    }
}

And the view:

<% using (Html.BeginForm()) { %>
    <%= Html.RadioButtonFor(m => m.RdPageType, true, new {id = "rdPageType" }) %>
    <%= Html.RadioButtonFor(m => m.RdPageType, false, new {id = "rdPageType12" }) %>    
    <input type="submit" value="OK" />
<% } %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM