I've an Hotel model and there is a HotelPrice list in the model.
What i'm trying to do is when user display hotel detail page let hotel prices' info be shown, also they can be editable. I've a breakfastIncluded property on HotelPrice instances which i have to display as radio button.
Here is my code:
<div>
@{
foreach(var hotelPrice in Model.HotelPrices)
{
<label class="mt-radio-inline>
@Html.RadioButtonFor(hotelModel => hotelPrice.breakfastIncluded, "1", new { @checked = (hotelPrice.Breakfast.ToString() == "1") })Yes
<span></span>
</label>
<label class="mt-radio-inline>
@Html.RadioButtonFor(hotelModel => hotelPrice.breakfastIncluded, "0", new { @checked = (hotelPrice.Breakfast.ToString() == "0") })No
<span></span>
</label>
}
}
When i display my page(i could not come editing part, yet), all breakfastIncluded properties' radio buttons are displayed as unassigned and the last one's radio button is displayed wrongly(i.e it has to be "Yes" but it seems like "No").
However, when i checked by Inspect tool of browser, all of the radio buttons' checked property appears correct(i.e if it should be "Yes" that radio button's checked is true and "No"'s checked is false).
I'm new to html and i could not figure out why that happens. Can you help me? Thanks in advance.
foreachloop to bind controls to a collection (refer this answer). And you do not set thecheckedattribute (theRadioButtonFor()will do that correctly when you fix your view (andchecked="true"orchecked="false"orchecked="anything"are all the same - they sets thecheckedstate but since only one can be checked, the last one is (and the property should be abool, not anint) - user3559349foreachwhen looping through collections to create Form elements. Always use e.g.for (var i = 0; i < Model.HotelPrices.Count; i++)and then@Html.RadioButtonFor(m => Model.HotelPrices[i], ... ). This is needed to generate element names that can be used by the model binding when the form is submitted. - Peter Bnew { @checked = "true" }, for "No"new { @checked = "false" }. Now all values appears as "No" whereas they have to appear as "Yes". @StephenMuecke i couldn't understand how i should correct checked parts. Also i couldn't understand what do you mean by saying " the last one is (and the property should be a bool, not an int)". If you can re-explain i'd be appreciated. - Dilara Albayraknew { @checked = "..." }- user3559349RadioButtonFor()method sets it correctly - it the value of the property is1the first one will be checked. If its0then the 2nd one will be - thats how model binding works - it binds to the value of your property - user3559349