Richard77
Richard77

Reputation: 21641

How can I get a radiobutton to be pre-selected in ASP.NET MVC 2?

Let's say I've this

public class OrganisationData
{
  public NavigationData navigationData {get; set; }
}

Then

public class NavigationData
{
  public string choice {get;set;}
  //other properties omitted
}

I've this on my view

<% Using(Html.BeginForm()){%>
   <p>
      <% = Html.RadioButtonFor(x => x.organizationData.navigationData.choice, "1")%>
   </p>
   //More choices
<%}%>

The first the user gets to that view I want the first RadioButton to be pre-selected.

Thanks for helping.

Upvotes: 2

Views: 1325

Answers (2)

Andrew Bullock
Andrew Bullock

Reputation: 37378

you should set the value in the Model that you send to the viewengine, from your GET controller action.

something like:

ActionResult MyMethod()
{
    var vm = new OrganisationData { NavigationData = new NavigationData{ choice = 1 } };
    return View("myview", vm);
}

Don't put logic in the view as John suggests, this is a massive design antipattern and will only cause you woe in the long run.

Edit:

passing the default to the view from the controller means the controller has made the decision as to what the default is. This is logic and therefore doesnt belong in the view. Doing it in the controller makes it testable.

Upvotes: 1

John Hartsock
John Hartsock

Reputation: 86882

Set the HTMLAttributes Object for the First Radio Button.

<% Using(Html.BeginForm()){%> 
   <p> 
      <% = Html.RadioButtonFor(x => x.organizationData.navigationData.choice, 
              "1", 
              new[] {checked="checked"})%> 
   </p> 
   //More choices 
<%}%> 

Upvotes: 2

Related Questions