sara
sara

Reputation: 166

RadioButtonFor not bind null value

I have this code

@Html.RadioButtonFor(model => model.LivStato, 1, Model.LivStato == 1)
@Html.RadioButtonFor(model => model.LivStato, -1, Convert.ToString(Model.LivStato) == string.Empty)

If Model.LivStato == 1 is true, the radio button is checked.

I don't understand why if Convert.ToString(Model.LivStato) == string.Empty is true, the radio button is not checked

I also try this

@Html.RadioButtonFor(model => model.LivStato, -1, !Model.LivStato.HasValue)

but don't work.

In the model:

public short? LivStato { get; set; }

Can anyone help me?

Upvotes: 3

Views: 7866

Answers (2)

ajbeaven
ajbeaven

Reputation: 9562

Updated answer

Oops, my original answer did not work if the null radio button was not first in the list. As noted by @sohtimsso1970, the radio button would have a checked attribute which would normally cause it to be selected even when the value is not null unless there was another checked radio button later down in the DOM, which of course there would be if the true/false-bound radio button came below null-bound one.

With this in mind, here's a better solution:

@{
    var dict = new Dictionary<string, object>();
    if (!Model.LivStato.HasValue) { dict.Add("checked", "checked"); }
}
<label>@Html.RadioButtonFor(model => model.LivStato, "", dict) Null</label>
<label>@Html.RadioButtonFor(model => model.LivStato, 1) +1</label>
<label>@Html.RadioButtonFor(model => model.LivStato, -1) -1</label>

This will work regardless of where the null-bound radio button is on the DOM and also renders the correct HTML.


Original answer:

Using the following radio button will bind to null:

<%: Html.RadioButtonFor(model => model.LivStato, "", new { @checked = !Model.LiveStato.HasValue }) %>

The checked attribute is required so the radio button is correctly checked when the ViewModel property is null.

Upvotes: 7

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

Look at HtmlHelper.RadioButtonFor overloads : no one uses a boolean third parameter as "check button if value == something". Third parameter (when it exists) is just here for htmlAttributes.

http://msdn.microsoft.com/en-us/library/ee830415%28v=vs.108%29

If your firstLine works, it's just because you use 1 as second parameter (Model.LivStato == 1 doesn't do anything).

You may try (untested)

@Html.RadioButtonFor(model => model.LivStato, 1)
@Html.RadioButtonFor(model => model.LivStato, -1)

and change -1 to null in your controller.

Upvotes: 3

Related Questions