views:

56

answers:

2

Hello,

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.

+1  A: 

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 
<%}%> 
John Hartsock
John Hartstock: I'm getting some wierd error, such as "An anonymous type cannot have multiple properties with the same name", and son on.
Richard77
look at my edit above. Sorry I forgot to enclose the value in quotes
John Hartsock
@John Hartstock: It still not working. I don't understand. I'm still getting the same error
Richard77
+1  A: 

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.

Andrew Bullock
@Andrew. he is asking to preselect or check the first radio button. I didnt put logic in the view but created a default for the view using the HTMLAttributes for the Method RadioButtonFor. Your solution will not check the radio when the view loads.
John Hartsock
setting it as checked with the htmlattributes is logic-in-the-view. if youre saying radiobuttonfor doesnt automatically check a checkbox if the property it points to has the value the radio button represents, then thats just pants ms code as usual. glad i don't use the webforms view engine! :)
Andrew Bullock
@Andrew Bullok: it's working.
Richard77