MVC 5 Razor view does not bind bool to input

I have a razor view (Framework 4.5, MVC 5) and an input type = flag with a number equal to the logical value of the model, but instead of true or false, it binds the β€œvalue”.

This is my code:

for (int index = 0; index < Model.Item1.Locations.Length; index++) { WSTupleOfInt32StringStringBoolean location = Model.Item1.Locations[index]; <div class="editor-field"> <input id="@string.Format("presentation.ServiceInfoes[{1}].Locations[{0}].Key", index, Model.Item2)" type="checkbox" value="@location.ThirdValue" name="@string.Format("presentation.ServiceInfoes[{1}].Locations[{0}].ThirdValue", index, Model.Item2)" /> </div> <div class="editor-label"> <label for="@string.Format("presentation.ServiceInfoes[{1}].Locations[{0}].Key", index, Model.Item2)">@location.FirstValue</label> @if (!string.IsNullOrEmpty(location.SecondValue)) { <a href="@string.Format("//maps.google.com/?q={0}", location.SecondValue)" target="_blank"><img alt="@location.SecondValue" src="@string.Format("//maps.google.com/maps/api/staticmap?center={0}&markers=color:blue|{0}&zoom=15&size=64x64&sensor=false", location.SecondValue)" /></a> } </div><br /> } 

location.ThirdValue is a boolean property debugging the it fine property. but in HTML I get value="value" , not value="false" .

What's happening?

+6
source share
2 answers

See Answer

Basically you want to use HTML.CheckBoxFor(model => model.booleanProperty)

+6
source

Do it

 <input id="@string.Format("presentation.ServiceInfoes[{1}].Locations[{0}].Key", index, Model.Item2)" type="checkbox" @(location.ThirdValue ? "checked" : "") name="@string.Format("presentation.ServiceInfoes[{1}].Locations[{0}].ThirdValue", index, Model.Item2)" /> 

The value does not check the checkbox or not, the value has a different function. For example, if you set the value to "test" and check the box, when you submit the form, you will see that instead of the true value of the transmitted variable, there will be "test";

You can make pretty cool stuff with it. For example, you have 3 checkboxes in your form. they all have the same name but different meanings. when submitting the form, the result obtained by you will be separated by a comma with the values ​​of the checked flags;

+1
source

Source: https://habr.com/ru/post/958790/


All Articles