从.NET Core MVC中的另一个模型中插入数据中的数据

发布于 2025-01-21 03:35:45 字数 3339 浏览 0 评论 0原文

我正在尝试构建一个测验应用程序,我想在提交测验后插入用户的答案。 这是我的问题模型:

public class Question
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Display(Name = "Id Question")]
    public int id_question { get; set; }

    [Column(TypeName = "varchar(100)")]
    [Display(Name = "Question")]
    public string question { get; set; }

    public string option1 { get; set; }
    public string option2 { get; set; }
    public string option3 { get; set; }
    public string option4 { get; set; }

    public string answer { get; set; }

    public virtual List<Result> Results { get; set; }
}

这是我想要存储用户答案的​​结果模型:

public class Result
{
    [Key]
    [Display(Name ="Id Result")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public int id_result { get; set; }

    [ForeignKey("User")]
    [Required]
    public string Id_User { get; set; }

    [Display(Name = "user")]
    [NotMapped]
    public string User_Name { get; set; }

    [ForeignKey("Question")]
    [Required]
    public int id_question { get; set; }

    [Display(Name = "Question")]
    [NotMapped]
    public string q { get; set; }
    public string UserAnswer { get; set; }
    public virtual ApplicationUser User { get; set; }
    public virtual Question Question { get; set; }
}

在数据库中存储考试问题后,我想像这样显示它们并在提交后存储答案:

@model IEnumerable<Exam.Areas.Identity.Data.Question>
@{
    ViewData["Title"] = "Exam";
}

<div>
    <h4>Question</h4>
    <hr />

    @foreach (var item in Model)
    {
        <div class="row pl-5">
            <div class="col-md-4">
                <div>@Html.DisplayFor(modelItem => item.question)</div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option1" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option1)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option2" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option2)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option3" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option3)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option4" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option4)
                    </label>
                </div>
            </div>
        </div>

    }

我尝试了很多事情徒然。谁能帮我想出一种方法来解决这个问题?

I'm trying to build a quiz application and i want to insert the user's answers after the quiz is submitted.
this is my question model:

public class Question
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Display(Name = "Id Question")]
    public int id_question { get; set; }

    [Column(TypeName = "varchar(100)")]
    [Display(Name = "Question")]
    public string question { get; set; }

    public string option1 { get; set; }
    public string option2 { get; set; }
    public string option3 { get; set; }
    public string option4 { get; set; }

    public string answer { get; set; }

    public virtual List<Result> Results { get; set; }
}

And this is the Result model where i want to store the user's answers:

public class Result
{
    [Key]
    [Display(Name ="Id Result")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public int id_result { get; set; }

    [ForeignKey("User")]
    [Required]
    public string Id_User { get; set; }

    [Display(Name = "user")]
    [NotMapped]
    public string User_Name { get; set; }

    [ForeignKey("Question")]
    [Required]
    public int id_question { get; set; }

    [Display(Name = "Question")]
    [NotMapped]
    public string q { get; set; }
    public string UserAnswer { get; set; }
    public virtual ApplicationUser User { get; set; }
    public virtual Question Question { get; set; }
}

After storing an exam's questions in the database I want to display them like this and store the answers after submitting them:

@model IEnumerable<Exam.Areas.Identity.Data.Question>
@{
    ViewData["Title"] = "Exam";
}

<div>
    <h4>Question</h4>
    <hr />

    @foreach (var item in Model)
    {
        <div class="row pl-5">
            <div class="col-md-4">
                <div>@Html.DisplayFor(modelItem => item.question)</div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option1" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option1)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option2" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option2)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option3" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option3)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option4" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option4)
                    </label>
                </div>
            </div>
        </div>

    }

I've tried many things in vain. Can anyone help me figure out a way to approach this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风流物 2025-01-28 03:35:45

从您回答的Rahul Sharma的评论来看,您的问题可能是如何将答案存储在结果表中。
如果我们想回答多个问题并将它们提交在一个页面中,则可以将问题和相应的答案传递给控制器​​作为列表集合,然后将它们存储在数据库中以进行调用。
如果允许调用多个模型加载数据,则可以参考以下示例代码。

模型:

Question.cs:

public class Question
{
        [Key]
        public int id_question { get; set; }

        [Column(TypeName = "varchar(100)")]
        [Display(Name = "Question")]
        public string question { get; set; }

        public string option1 { get; set; }
        public string option2 { get; set; }
        public string option3 { get; set; }
        public string option4 { get; set; }

        public string answer { get; set; }

}

result.cs:

public class Result
{
        [Key]
        [Display(Name = "Id Result")]
        public int id_result { get; set; }
        [Required]
        public int Id_User { get; set; }
        [Required]
        public string User_Name { get; set; }

        [ForeignKey("Question")]
        [Required]
        public int id_question { get; set; }

        public string q { get; set; }
        public string UserAnswer { get; set; }
}

applicationuser.cs:

public class ApplicationUser
{
        [Key]
        [Required]
        public int Id { get; set; }
        [Required]
        public int Id_User { get; set; }
        [Required]
        public string User_Name { get; set; }   
}

控制器:
QuestionAndResultController.cs:

public class QuestionAndResultController : Controller
{

        private readonly MyDbContext _myDbContext;

        public QuestionAndResultController(MyDbContext myDbContext)
        {
            _myDbContext = myDbContext;

        }

       
        public async Task<IActionResult> Index()
        {
            var question = from m in _myDbContext.Question
                           select m;
            ViewBag.UserRecord = await (from m in _myDbContext.ApplicationUser select m).ToListAsync();
            ViewBag.ResultRecord = await (from m in _myDbContext.Result select m).ToListAsync();
            
            return View(await question.ToListAsync());
        }

        [HttpGet]
        public async Task<IActionResult> ResultAnswer()
        {
            var  question = await (from m in _myDbContext.Question select m).ToListAsync();
            ViewBag.Question = question;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ResultAnswer(int Id_User,List<int> id_question, List<string> UserAnswer, List<string> q,string User_Name)
        {
            if (ModelState.IsValid)
            {
                var UserRecord = await (from m in _myDbContext.ApplicationUser select m).ToListAsync();
                bool Exist = false;
                foreach (var item in UserRecord)
                {
                    if (item.Id_User == Id_User && item.User_Name == User_Name)
                        Exist = true;
                }
                if (!Exist)
                {
                    ApplicationUser user = new ApplicationUser();
                    user.Id_User = Id_User;
                    user.User_Name = User_Name;
                    _myDbContext.ApplicationUser.Add(user);
                    await _myDbContext.SaveChangesAsync();
                    for (int i = 0; i < UserAnswer.Count; i++)
                    {
                        Result result = new Result();
                        result.Id_User = Id_User;
                        result.id_question = id_question[i];
                        result.UserAnswer = UserAnswer[i];
                        result.User_Name = User_Name;
                        result.q = q[i];
                        _myDbContext.Result.Add(result);
                        await _myDbContext.SaveChangesAsync();
                    }
                }
                else
                { 
                    var ResultRecord = await (from m in _myDbContext.Result select m).ToListAsync();
                    foreach (var item in ResultRecord)
                    {
                        if (item.Id_User == Id_User && item.User_Name == User_Name)
                        {
                            for (int i = 0; i < UserAnswer.Count; i++) {
                                if (item.id_question == id_question[i])
                                {
                                    item.UserAnswer = UserAnswer[i];
                                    _myDbContext.Result.Update(item);
                                    await _myDbContext.SaveChangesAsync();
                                }
                            }
                        }
                    }
                }
                
                return RedirectToAction(nameof(Index));
            }
            return View();
        }
}

视图:
index.cshtml:

@model IEnumerable<TableTest.Models.Question>

@{
    ViewData["Title"] = "Index";
}

<h1>Question</h1>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.question)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option1)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option2)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option3)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option4)
            </th>
            <th>
               @Html.DisplayNameFor(model => model.answer)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model) {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.question)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option1)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option2)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option3)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option4)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.answer)
                </td>
            </tr>
        }
    </tbody>
</table>
<a class="btn btn-primary" asp-action="ResultAnswer">answer</a>

<h1>Result</h1>
<table class="table">
    <thead>
        <tr>
            <th>id_user</th>
            <th>user_name</th>
            @for (var i = 0; i < @Model.Count(); i++)
            {
                <th>qurstion@(i+1)</th>
                <th>UserAnswer</th>
            }
        </tr>
    </thead>
    <tbody>
            @foreach (var itemUser in @ViewBag.UserRecord)
            {
                <tr>
                    <td>@itemUser.Id_User</td>
                    <td>@itemUser.User_Name</td>
                    @foreach (var itemResult in @ViewBag.ResultRecord)
                    {
                        @if (@itemResult.Id_User == @itemUser.Id_User && @itemResult.User_Name == @itemUser.User_Name)
                        {
                            <td>@itemResult.q</td>
                            <td>@itemResult.UserAnswer</td>
                        }
                    }
                </tr>
            }
   </tbody>
    
</table>

ResultAnswer.cshtml:
@model TableTest.Models.Result

@{
    ViewData["Title"] = "Login";
}

<div class="row">
    <div class="col-md-4">
        <form asp-action="ResultAnswer">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Id_User" class="control-label"></label>
                <input asp-for="Id_User" class="form-control" />
                <span asp-validation-for="Id_User" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label asp-for="User_Name" class="control-label"></label>
                <input asp-for="User_Name" class="form-control" />
                <span asp-validation-for="User_Name" class="text-danger"></span>
            </div>
            
            <div>Below is the question</div>
            @foreach (var item in @ViewBag.Question)
            {
                <div>@item.question</div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option1" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option1
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option2" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option2
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option3" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option3
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option4" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option4
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <input type="hidden" asp-for="UserAnswer" id="@item.id_question" />
                <input type="hidden" asp-for="id_question" value = "@item.id_question"/>
                <input type="hidden" asp-for="q" value = "@item.question"/>
            }
            <div class="form-group">
                <input type="submit" value="Submit" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script>
    $('input[type=checkbox]').change(function(){
          if($(this).is(":checked")){
              var value = this.attributes.name.value;
              var id = this.attributes.value.value;
              $("#"+id).attr("value",value);  
          }
          
    })
</script>

测试结果:

索引页:

“

单击“答案”:

单击“提交”:

”在此处输入图像描述

Judging by Rahul Sharma's comment you responded to, your question might be how to store the answer in the Results table.
If we want to answer multiple questions and submit them in one page, we can pass the questions and corresponding answers back to the controller as a List collection and store them in the database to call.
If you allow calling multiple models to load data, you can refer to the following sample code.

Models:

Questions.cs:

public class Question
{
        [Key]
        public int id_question { get; set; }

        [Column(TypeName = "varchar(100)")]
        [Display(Name = "Question")]
        public string question { get; set; }

        public string option1 { get; set; }
        public string option2 { get; set; }
        public string option3 { get; set; }
        public string option4 { get; set; }

        public string answer { get; set; }

}

Result.cs:

public class Result
{
        [Key]
        [Display(Name = "Id Result")]
        public int id_result { get; set; }
        [Required]
        public int Id_User { get; set; }
        [Required]
        public string User_Name { get; set; }

        [ForeignKey("Question")]
        [Required]
        public int id_question { get; set; }

        public string q { get; set; }
        public string UserAnswer { get; set; }
}

ApplicationUser.cs:

public class ApplicationUser
{
        [Key]
        [Required]
        public int Id { get; set; }
        [Required]
        public int Id_User { get; set; }
        [Required]
        public string User_Name { get; set; }   
}

Controller:
QuestionAndResultController.cs:

public class QuestionAndResultController : Controller
{

        private readonly MyDbContext _myDbContext;

        public QuestionAndResultController(MyDbContext myDbContext)
        {
            _myDbContext = myDbContext;

        }

       
        public async Task<IActionResult> Index()
        {
            var question = from m in _myDbContext.Question
                           select m;
            ViewBag.UserRecord = await (from m in _myDbContext.ApplicationUser select m).ToListAsync();
            ViewBag.ResultRecord = await (from m in _myDbContext.Result select m).ToListAsync();
            
            return View(await question.ToListAsync());
        }

        [HttpGet]
        public async Task<IActionResult> ResultAnswer()
        {
            var  question = await (from m in _myDbContext.Question select m).ToListAsync();
            ViewBag.Question = question;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ResultAnswer(int Id_User,List<int> id_question, List<string> UserAnswer, List<string> q,string User_Name)
        {
            if (ModelState.IsValid)
            {
                var UserRecord = await (from m in _myDbContext.ApplicationUser select m).ToListAsync();
                bool Exist = false;
                foreach (var item in UserRecord)
                {
                    if (item.Id_User == Id_User && item.User_Name == User_Name)
                        Exist = true;
                }
                if (!Exist)
                {
                    ApplicationUser user = new ApplicationUser();
                    user.Id_User = Id_User;
                    user.User_Name = User_Name;
                    _myDbContext.ApplicationUser.Add(user);
                    await _myDbContext.SaveChangesAsync();
                    for (int i = 0; i < UserAnswer.Count; i++)
                    {
                        Result result = new Result();
                        result.Id_User = Id_User;
                        result.id_question = id_question[i];
                        result.UserAnswer = UserAnswer[i];
                        result.User_Name = User_Name;
                        result.q = q[i];
                        _myDbContext.Result.Add(result);
                        await _myDbContext.SaveChangesAsync();
                    }
                }
                else
                { 
                    var ResultRecord = await (from m in _myDbContext.Result select m).ToListAsync();
                    foreach (var item in ResultRecord)
                    {
                        if (item.Id_User == Id_User && item.User_Name == User_Name)
                        {
                            for (int i = 0; i < UserAnswer.Count; i++) {
                                if (item.id_question == id_question[i])
                                {
                                    item.UserAnswer = UserAnswer[i];
                                    _myDbContext.Result.Update(item);
                                    await _myDbContext.SaveChangesAsync();
                                }
                            }
                        }
                    }
                }
                
                return RedirectToAction(nameof(Index));
            }
            return View();
        }
}

View:
Index.cshtml:

@model IEnumerable<TableTest.Models.Question>

@{
    ViewData["Title"] = "Index";
}

<h1>Question</h1>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.question)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option1)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option2)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option3)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option4)
            </th>
            <th>
               @Html.DisplayNameFor(model => model.answer)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model) {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.question)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option1)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option2)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option3)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option4)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.answer)
                </td>
            </tr>
        }
    </tbody>
</table>
<a class="btn btn-primary" asp-action="ResultAnswer">answer</a>

<h1>Result</h1>
<table class="table">
    <thead>
        <tr>
            <th>id_user</th>
            <th>user_name</th>
            @for (var i = 0; i < @Model.Count(); i++)
            {
                <th>qurstion@(i+1)</th>
                <th>UserAnswer</th>
            }
        </tr>
    </thead>
    <tbody>
            @foreach (var itemUser in @ViewBag.UserRecord)
            {
                <tr>
                    <td>@itemUser.Id_User</td>
                    <td>@itemUser.User_Name</td>
                    @foreach (var itemResult in @ViewBag.ResultRecord)
                    {
                        @if (@itemResult.Id_User == @itemUser.Id_User && @itemResult.User_Name == @itemUser.User_Name)
                        {
                            <td>@itemResult.q</td>
                            <td>@itemResult.UserAnswer</td>
                        }
                    }
                </tr>
            }
   </tbody>
    
</table>

ResultAnswer.cshtml:
@model TableTest.Models.Result

@{
    ViewData["Title"] = "Login";
}

<div class="row">
    <div class="col-md-4">
        <form asp-action="ResultAnswer">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Id_User" class="control-label"></label>
                <input asp-for="Id_User" class="form-control" />
                <span asp-validation-for="Id_User" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label asp-for="User_Name" class="control-label"></label>
                <input asp-for="User_Name" class="form-control" />
                <span asp-validation-for="User_Name" class="text-danger"></span>
            </div>
            
            <div>Below is the question</div>
            @foreach (var item in @ViewBag.Question)
            {
                <div>@item.question</div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option1" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option1
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option2" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option2
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option3" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option3
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option4" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option4
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <input type="hidden" asp-for="UserAnswer" id="@item.id_question" />
                <input type="hidden" asp-for="id_question" value = "@item.id_question"/>
                <input type="hidden" asp-for="q" value = "@item.question"/>
            }
            <div class="form-group">
                <input type="submit" value="Submit" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script>
    $('input[type=checkbox]').change(function(){
          if($(this).is(":checked")){
              var value = this.attributes.name.value;
              var id = this.attributes.value.value;
              $("#"+id).attr("value",value);  
          }
          
    })
</script>

Test Result:

Index page:

enter image description here

Click on "answer":

enter image description here

Click on "Submit":

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文