1

I have a problem for which I just can't find a solution.

Checking button like this works:

@Html.RadioButtonFor(x => x.an2[0], 3, Model.an2[0]==3 
    ? new { id = "B", @checked = "checked" } : null)

But I also need to set id, how do I do that? This code:

@Html.RadioButtonFor(x => x.an2[0], 3, Model.an2[0]==3 
    ? new { id = "B", @checked = "checked" } : new { id = "B" })

Gives error:

Type of conditional expression cannot be determined because there is no implicit conversion between 'AnonymousType#1' and 'AnonymousType#2'

Which is beyond my understanding.

I suppose there should be a trivial solution to this?

Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56
Mark_856
  • 13
  • 4
  • While Sam Farajpour Ghamari's answer shows you how to create conditional html attributes, it is completely unnecessary in your case. You should never set the `checked` attribute when using `RadioButtonFor()`. The helper already sets it based on the value if the property your binding to (and if its not, then you have other problems with your code) –  Aug 09 '15 at 01:40
  • I tried and it doesen't work in my case. What I'm trying to create is a test, where user switches through partialviews and selects the answer he/she thinks is correct. If going to previous partialview I want that previously selected answer (radiobutton) is checked, but can be changed. With my code and Sam's correction, the wanted effect takes place. If I remove the "checked" part it does not, even though the model that contains an2 list is passed back and forth. – Mark_856 Aug 09 '15 at 02:28
  • Then there is something else wrong in your code, so perhaps you should also consider addressing that as well ") –  Aug 09 '15 at 02:34

2 Answers2

1

Cast them to object:

Html.RadioButtonFor(x => x.an2[0], 3, Model.an2[0]==3 
    ? (object)new { id = "B", @checked = "checked" } : (object)new { id = "B" });
Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56
0

Check this link.

@{string id = ViewData.TemplateInfo.GetFullHtmlFieldId("radioTrue");}
@Html.RadioButtonFor(x => x.an2[0], 3, Model.an2[0]==3 ? new { id } : null)

A good example of this is here.

Community
  • 1
  • 1
pool pro
  • 2,084
  • 12
  • 21