SRA
SRA

Reputation: 1691

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

Upvotes: 0

Views: 1606

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

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

Upvotes: 1

Related Questions