簡體   English   中英

如何從MVC5中的視圖動態保存數據

[英]How to save data dynamically from a View in MVC5

我想建立一個問卷調查MVC5項目。 我有一個帶有多個表的MSSQL數據庫,例如:員工,問題,結果...

我創建了一個新的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,用兩個文本區域顯示每個問題,一個用於答案,一個用於一些附加信息:

@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中保存QuestionID,Answer和Document。 在webforms中,我創建了一個usercontrol,然后使用Foreach usercontrol並保存到數據庫。

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

這是QuestionsModel:

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; }
    }
}

這是ResultsMOdel:

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; }
    }
}

這是用於生成問卷視圖的問卷動作結果:

    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()方法將基於模板為每個Question生成html,並且重要的是將添加正確的name屬性,以使您的表單控件能夠回發並綁定到模型

控制器中的

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屬性,因此如果要添加,則不清楚每個問題有多個答案和文檔,或者只有一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM