0

Is it possible to create dropdown list for bool model property with custom text, using html helpers. I have a model:

public class Script
public bool HasTopics { get; set; } 

I tried:

@Html.DropDownListFor(model => model.HasTopics, new SelectList(ViewBag.HasTopics, "Value", "Text"))

In viewbag there is a collection:

ViewBag.HasTopics = new SelectList(
new[]
{
    new {Value = true, Name="Selected"},
    new {Value = false, Name="Not selected"}
},
"Value", "Name");

But i can't solve a few problems:

  1. HasTopics store in model picked value but it doesn't pass to controll. Every time I'm opening the form it showing default (first item in list) value.
  2. Is there a way using model atributes to set the name of bool variable?

Update #1 Yong Shun suggested topic but I think i did something wrong and it still doesn't work as I want. I tried: This helper generates id and name and pass the value to action but it doesn't pick field property from model.

@Html.DropDownList(@Html.IdFor(m => m.HasTopics).ToString(), new SelectList( new[] { new { Value = true, Text = "Yes" }, new { Value = false, Text = "No" },},"Value", "Text", Model.HasTopics))

This one works well but it doesn't pass the value to action

@Html.DropDownList("RandomId", new SelectList( new[] { new { Value = true, Text = "Yes" }, new { Value = false, Text = "No" },},"Value", "Text", Model.HasTopics))

There is a combination of first and seccond approach but result as at first one it still don't want change to the value which hold's in model (in form).

@Html.DropDownList("HasTopics", new SelectList( new[] { new { Value = true, Text = "Yes" }, new { Value = false, Text = "No" },},"Value", "Text", Model.HasTopics))

And there is last one I tried same as previous.

@Html.DropDownListFor(m => m.HasTopics, new SelectList(new[] {new { Value = true, Text = "Yes" }, new { Value = false, Text = "No" },}, "Value", "Text", Model.HasTopics))

Also changed false to "false" and Model.HasTopics to Model - no result.

enter image description here

TryHard
  • 125
  • 9
  • Does this answer your question? [Convert a boolean property editor to a dropdownlist in MVC view](https://stackoverflow.com/questions/15479791/convert-a-boolean-property-editor-to-a-dropdownlist-in-mvc-view) – Yong Shun Feb 10 '22 at 00:55
  • @Yong Shun i tried but it still doesn't work explain in topic – TryHard Feb 10 '22 at 05:22

0 Answers0