如何从 MVC5 中的视图动态保存数据

How to save data dynamically from a View in MVC5

我想构建一个问卷调查 MVC5 项目。 我有一个包含多个表的 MSSQL 数据库,例如:Employee、Questions、Results ...

我创建了一个新的 MVC5 项目,我将它添加到基于我的数据库的模型中,并且我管理所有需要它的 CRUD 操作。

现在我为Questionar做了一个观点:

@model IEnumerable<ChestionarMVC.Models.FormQuestion>

@{
    ViewBag.Title = "Chestionar";
}

<h2>Chestionar</h2>

    @foreach (var item in Model)
    {
   @Html.Partial("_Chestionar",item)
    }
<input id="Submit1" type="submit" value="submit" />

还有一个 partialView 用于显示每个问题的 2 个文本区域,一个用于答案,一个用于一些附加信息:

@model ChestionarMVC.Models.FormQuestion

<table border="1" style="width:100%">

        <tr>
            <td>
                @Html.DisplayFor(modelItem => Model.Question)
            </td>

        </tr>
        <tr>
            <td>
                Raspuns <br />
                <textarea id="TextArea1" rows="2" cols="80" style="width:800px; height:100px;"></textarea>
            </td>
        </tr>
        <tr>
            <td>
                Document <br />
                <textarea id="TextArea2" rows="2" cols="80" style="width:400px"></textarea>
            </td>
        </tr>
</table>

现在我想在 tblResults 中保存问题 ID、答案和文档。 在 webforms 中我做了一个用户控件,然后我使用了 Foreach 用户控件,并保存到数据库中。

在 MVC 中如何保存所有内容?

这是问题模型:

namespace ChestionarMVC.Models
{
    using System;
    using System.Collections.Generic;

    public partial class FormQuestion
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public FormQuestion()
        {
            this.FormResults = new HashSet<FormResult>();
            this.TBLPos = new HashSet<TBLPos>();
        }

        public int idQuestion { get; set; }
        public string Question { get; set; }
        public int idCategory { get; set; }
        public int idPosition { get; set; }
        public Nullable<int> Ordine { get; set; }

        public virtual FormCategory FormCategory { get; set; }
        public virtual Formular Formular { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<FormResult> FormResults { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<TBLPos> TBLPos { get; set; }
    }
}

这是结果模型:

namespace ChestionarMVC.Models
{
    using System;
    using System.Collections.Generic;

    public partial class FormResult
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public FormResult()
        {
            this.Documentes = new HashSet<Documente>();
        }

        public int idResult { get; set; }
        public int idUser { get; set; }
        public int idQuestion { get; set; }
        public string Answer { get; set; }
        public string RefferenceDocument { get; set; }
        public Nullable<System.DateTime> StampDate { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Documente> Documentes { get; set; }
        public virtual Employee Employee { get; set; }
        public virtual FormQuestion FormQuestion { get; set; }
    }
}

这是用于生成问卷视图的问卷 ActionResult:

    public ActionResult Chestionar()
    {
        var formQuestions = db.FormQuestions;
        return View(formQuestions.ToList());
    } 

首先创建一个包含视图所需属性的视图模型(请注意根据需要添加其他验证属性以满足您的需要)

public class QuestionVM
{
  public int ID { get; set; }
  public string Question { get; set; }
  [Required(ErrorMessage = "Please enter and answer")]
  public string Answer { get; set; }
  public string Document { get; set; }
}

然后创建一个EditorTemplate。在/Views/Shared/EditorTemplates/QuestionVM.cshtml

@model QuestionVM
@Html.HiddenFor(m => m.ID)
@Html.HiddenFor(m => m.Question)
@Html.DisplayNameFor(m => m.Question)
@Html.DisplayFor(m => m.Question)
@Html.LabelFor(m => m.Answer)
@Html.TextAreaFor(m => m.Answer)
@Html.ValidationMessageFor(m => m.Answer)
... // ditto for Document (as for Answer)

并且在主视图中

@model IEnumerable<QuestionVM>
@using (Html.BeginForm())
{ 
  @Html.EditorFor(m => m)
  <input type="submit" ... />
}

请注意,EditorFor() 方法将根据模板为每个问题生成 html,并且重要的是将添加正确的名称属性,使您的表单控件能够回发并绑定到你的模特

控制器中的

public ActionResult Chestionar()
{
  // Get data model and map to view models
  var model = db.FormQuestions.Select(q => new QuestionVM()
  {
    ID = q.idQuestion,
    Question = q.Question,
    Answer = .....,
    Document = .... // see notes below
  };
  return View(model);
}
[HttpPost]
public ActionResult Chestionar(IEnumerable<QuestionVM> model)
{
  if (!ModelState.IsValid)
  {
    return View(model);
  }
  // Get the data model again, map the view model properties back to the data model
  // update properties such as user and date
  // save and redirect
}

旁注:您的问题指示每个问题的(一个)答案和文档,但您当前的问题模型有一个集合(ICollection<FormResult> FormResults),其中包含 AnswerRefferenceDocument 所以不清楚你是想为每个问题添加多个答案和文档,还是只添加一个。