Link to home
Create AccountLog in
Avatar of Babak Sekandari
Babak SekandariFlag for United States of America

asked on

How do I persist data through an ASP.NET MVC Core app ?

I have an ASP.NET MVC Core project.

In a view, Index.cshtml, I want to ask a series of true/false questions (I don’t know how many yet and I don’t know what they are yet).

If the user answers a certain percentage true, then I want to takes some action based on that.

I have a code solution that works, but it feels clunky. I feel like there is a better way of doing the same thing.

Please review the following code and let me know if there is a better way to do this.

Here is the Questions class:

public class Questions
    public bool Question1 { get; set; } = false;
    public bool Question2 { get; set; } = false;
    public bool Question3 { get; set; } = false;
    public bool Question4 { get; set; } = false;
    public bool Question5 { get; set; } = false;
    public List<bool> AllQuestions { get; set; }
    public int NumQuestionsTrue()
        AllQuestions = new List<bool>();

        return AllQuestions.Count(q => q == false);

Open in new window


Here is the Index.cshtml:

@model WebApplication1.Data.Questions
<div class="container">
    <h1 class="display-4">Welcome</h1>
        Lorem ipsum dolor sit amet. 
        Volutpat maecenas volutpat blandit aliquam etiam erat velit.
    <form asp-controller="Home" asp-action="Index" method="post">
        <input type="checkbox" class="chk" asp-for="@Model.Question1" />
        <label asp-for="Question1">Senectus et netus et malesuada fames ac turpis egestas sed.</label><br>
        <input type="checkbox" class="chk" asp-for="Question2" />
        <label asp-for="Question2">Pellentesque nec nam aliquam sem et tortor consequat id porta. </label><br>
        <input type="checkbox" class="chk" asp-for="@Model.Question3" />
        <label asp-for="Question3">Posuere sollicitudin aliquam ultrices sagittis orci a scelerisque purus. </label><br>
        <input type="checkbox" class="chk" asp-for="@Model.Question4" />
        <label asp-for="Question4">Sapien eget mi proin sed libero enim sed faucibus turpis. </label><br>
        <input type="checkbox" class="chk" asp-for="@Model.Question5" />
        <label asp-for="Question5">Sollicitudin tempor id eu nisl nunc mi ipsum faucibus vitae.</label><br>
        <button type="submit">Submit</button>

Open in new window


Here is the Action class in the Home controller:

public IActionResult Index(Questions questions)
    bool sendPrescription;
    if (questions.NumQuestionsTrue() >= 3)
        sendPrescription = true;
    return View();

Open in new window

I thought about having the Questions class implement IEnumerable, but I'm going to wait and see what the suggestions here are.

Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account