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

时间:2015-08-23 12:33:13

标签: c# asp.net asp.net-mvc-3 asp.net-mvc-4 entity-framework-6

我想建立一个问卷调查MVC5项目。 我有一个MSSQL数据库,有几个表,如:Employee,Questions,Results ...

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

现在我对问号进行了观察:

@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中保存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; }
    }
}

这是问卷调查ActionResult用于生成调查问卷 - 视图:

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

1 个答案:

答案 0 :(得分:1)

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

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),其中包含Answer和{{1}的属性所以不清楚你是否想为每个问题添加多个答案和文档,或者只是一个。