Home > database >  ASP.NET Core : asp-for using a string as input
ASP.NET Core : asp-for using a string as input

Time:11-23

Would it be possible to dynamically create an asp-for on basis of a enum class?

@foreach (MyClass.MyOption item in Enum.GetValues(typeof(MyClass.MyOption)))
{
        var checkboxName = $"MyClass.CheckBox{item}";

        <label asp-for="@checkboxName" >
            <input type="checkbox" asp-for="@checkboxName"  value="true" name="@checkboxName" />
        </label><br/>
}

With these definitions of MyRequest:

public static class MyClass
{
    public enum MyOption : byte
    {
        First = 0,
        Second = 2,
        Third = 4
    }

    public class MyRequest
    {
        public bool CheckBoxFirst { get; set; }
        public bool CheckBoxSecond { get; set; }
        public bool CheckBoxThird { get; set; }
    }
}

When I do so, I run into the error:

InvalidOperationException: Unexpected expression result value 'MyClass.CheckBoxFirst' for asp-for. 'MyClass.CheckBoxFirst' cannot be parsed as a 'System.Boolean'.

Preferably it would also be my preference to even dynamically creating the bool functions in MyRequest (CheckBoxFirst, CheckBoxSecond, etc).

Tried with above code, but only the asp-for in the input type seems not to work, due to the parsing error.

CodePudding user response:

how will it then bind to the MyRequest booleans?

  1. use name="@checkboxName"

2.change the checkboxName into $"MyRequest.CheckBox{item}"

Try the below code:

<form  asp-action="Index" method="post">
    @foreach (MyClass.MyOption item in Enum.GetValues(typeof(MyClass.MyOption)))
{
        var checkboxName = $"MyRequest.CheckBox{item}";

        <label name="@checkboxName" id="@checkboxName" >
        
        </label><br/>
         <input type="checkbox"   value="true" name="@checkboxName" id="@checkboxName"/>
}
<input  type="submit"  value="create"/>
</form>

DynamicaspforController:

public class DynamicaspforController : Controller
    {
     
        public IActionResult Index()
        { return View(); }

        [HttpPost]
        public IActionResult Index( MyRequest myRequest)
        {
            return View();
        }
    }

result:

enter image description here

  • Related