0

So I'm trying to create a little tool where a user can select a set of days. I however need quite a complex model for extra data.

public class DayRange{
    ...
    List<DaySelected> Days
    ...
}
   
public class DaySelected{
    public bool Selected{ get; set;}
    public string DayName {get; set;}
    public DaySelected(string Day){
        Selected = false;
        DayName = day;
    }
}

My Razorpage looks like this:

@Model DayRange
...
<form asp-action="RegisterSelection" asp-controller="DayRegister">
<table>
@foreach (var Day in Model.Days)
{
    <tr>
        <td>
            <input [email protected] />
        </td>                                                            
    </tr>
}
</table>
<button type="submit">Confirm</button>

</form>

My method Registerselection looks like this:

[HttpPost]
public IActionResult RegisterSelection(DayRange dr){
    ...
}

However, whenever I change any of textboxes, all of the selected bool values remain the same. Can anybody help me on my way? Thanks in advance!

1 Answer 1

1

Here is a demo to pass data to action correctly:

Model:

public class DayRange
    {
        public List<DaySelected> Days { get; set; }
    }

    public class DaySelected
    {
        public bool Selected { get; set; }
        public string DayName { get; set; }
        public DaySelected()
        {
           
        }
        public DaySelected(string Day)
        {
            Selected = false;
            DayName = Day;
        }
    }

View:

@Model DayRange
<form asp-action="RegisterSelection" asp-controller="DayRegister">
    <table>
        @{ var i = 0;}
        @foreach (var Day in Model.Days)
        {
            <tr>
                <td>
                    <input [email protected] name="Days[@i].Selected" />
                    @Day.DayName
                    <input [email protected] name="Days[@i].DayName" hidden />
                </td>
            </tr>
            i ++;
        }
    </table>
    <button type="submit">Confirm</button>

</form>

result: enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the demo! I was able to make it work now, so I've accepted your answer as the solution for this issue. I'm simply wondering, was the reason that it didn't work simply because I didn't fill in the name of the components of the checkboxes? My apologies for the simple question, this is mostly new to me.
Yes,.net core bind data with name attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.