MVC ASP.NET 5实体框架通过范围输入收集表单数据 [英] MVC 5 ASP.NET Entity Framework Collect Form Data through Range Input

查看:92
本文介绍了MVC ASP.NET 5实体框架通过范围输入收集表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我创建一个调查猴子,调查4个类别,每个类别有5个问题,HomeController的指数经过从问题实体的20个问题,每个问题都必须有一个范围滑块从一到5个值的形式的值必须被收集到一个控制器中的方法,然后累积到QuestionResults表和处理,则它们必须被传递到CategoryResults和的每个类别,走出4,必须有一个累积得分,它们必须再为相比于CategoryFeedback(它是静态的)表,并显示正确的信息。在code为我的HomeController和它的指数是如下图所示。

这是我遇到的主要问题,是因为我在表单值通过作为的FormCollection的参数,我努力保持属于类问题的关系,然后这些都传递到CategoryResult表处理。

任何帮助将大大AP preciated

型号:

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;命名空间STRA.Models
{
    公共类问题
    {
        公众诠释标识{搞定;组; }
        公共字符串名称{搞定;组; }
        公共字符串CreatedBy {搞定;组; }
        公众的DateTime? dateCreated会获得{;组; }
        公众的DateTime? DateModified {搞定;组; }
        公共虚拟分类分类{搞定;组; }
        公众诠释的CategoryId {搞定;组; }
        公共虚拟的ICollection< QuestionResult> QuestionResult {搞定;组; }
        公共虚拟的ICollection< QuestionFeedback> QuestionFeedback {搞定;组; }
    }
}

QuestionResult

 使用IdentitySample.Models;
使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;命名空间STRA.Models
{
    公共类QuestionResult
    {
        公众诠释标识{搞定;组; }
        公众的DateTime? dateCreated会获得{;组; }
        公众的DateTime? DateModified {搞定;组; }
        公众诠释QuestionScore {搞定;组; }
        //导航属性
        公共虚拟ApplicationUser用户{搞定;组; }
        公众的ICollection< CategoryResult> CategoryResult {搞定;组; }
        公共虚拟问题问题{搞定;组; }
        公众诠释QuestionId {搞定;组; }
    }
}

CategoryResult

 使用IdentitySample.Models;
使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;命名空间STRA.Models
{
    公共类CategoryResult
    {
        公众诠释标识{搞定;组; }
        公众诠释CategoryScore {获取;设置;}
        //导航属性
        公共虚拟QuestionResult QuestionResult {搞定;组; }
        公众诠释QuestionResultId {搞定;组; }    }
}

任何帮助将大大AP preciated。
HomeController的指数

  @model IEnumerable的< STRA.Models.Question>
@ {
    //ViewBag.Question.Title =调查;
    布局=〜/查看/共享/ _QuizLayout.cshtml}< D​​IV CLASS =HR HR-18 HR-双点>< / DIV>< D​​IV CLASS =小工具盒>
    < D​​IV CLASS =窗口小部件的头部件头 - 蓝色小工具头平>
        < H4类=窗口小部件标题打火机>&STRA LT; / H4>        @ *< D​​IV CLASS =小窗口的工具栏>
                <标签>
                    <小班=绿色>
                        < B>验证和LT; / B>
                    < /小>                    <输入ID =跳过验证类型=复选框级=王牌王牌王牌切换开关-4/>
                    <跨度类=LBL中间的>< / SPAN>
                < /标签>
            < / DIV> * @
    < / DIV>
    @ *创建,家* @
    @using(Html.BeginForm(创建,家,FormMethod.Post))
    {
        @ Html.AntiForgeryToken()        < D​​IV CLASS =小工具体>
            < D​​IV CLASS =部件 - 主>
                < - #section:插件/ fuelux.wizard - >
                < D​​IV ID =fuelux精灵容器>
                    < D​​IV CLASS =COL-MD-12中心>
                        < D​​IV CLASS =易饼图百分比数据百分比=25数据色=#2679b5>
                            @ *下;跨度类=百分之> 20℃/跨度>%* @
                        < / DIV>
                    < / DIV>
                    < D​​IV的风格=显示:无;>                        < - #section:插件/ fuelux.wizard.steps - >
                        < UL类=步骤>
                            &所述;利数据两步=1类=活性>
                                &所述;跨度类=步骤→1&下; /跨度>
                                <跨度类=Question.Title>验证状态和LT; / SPAN>
                            < /李>                            <李数据步=2>
                                &所述;跨度类=步骤→2&下; /跨度>
                                <跨度类=Question.Title>警报< / SPAN>
                            < /李>                            <李数据步=3>
                                &所述;跨度类=步骤→3&下; /跨度>
                                <跨度类=Question.Title>付款方式< / SPAN>
                            < /李>                            <李数据步=4>
                                &所述;跨度类=步骤→4&下; /跨度>
                                <跨度类=Question.Title>其他信息< / SPAN>
                            < /李>
                        < / UL>                        &所述;! - /section:plugins/fuelux.wizard.steps - >
                    < / DIV>                    <小时/>                    < - #section:插件/ fuelux.wizard.container - >
                    < D​​IV CLASS =步内容POS-REL>
                        < D​​IV CLASS =一步窗格中的数据步=1>
                            @ {        的foreach(在Model.Take变种(5)项)
        {            < D​​IV CLASS =COL-MD-12>
                < H4> @ Html.DisplayFor(modelItem => item.Title)LT; / H4>                < D​​IV ID =滑块当量>
                    < H5类=拉左>强烈反对和LT; / H5>
                    < H5类=右拉>强烈同意与LT; / H5>
                    &所述;跨度的id =q_@Html.DisplayFor(modelItem = GT; item.Id)类=UI-滑块 - 紫色→3&下; /跨度>
                    <输入类型=隐藏ID =question_@item.IdNAME =question_@item.IdVALUE =3/>
                < / DIV>
            < / DIV>        }
        //Model.Skip(5);
                            }
                        < / DIV>
                        < D​​IV CLASS =一步窗格中的数据步=2>
                            @ *< D​​IV CLASS =中心>
                                    < H3类=蓝色打火机>这是一步2'; / H3 GT&;
                                < / DIV> * @
                            @ {
        的foreach(在Model.Skip变种(5)项。取(5))
        {
            < D​​IV CLASS =COL-MD-12>
                < H4> @ Html.DisplayFor(modelItem => item.Title)LT; / H4>
                < D​​IV ID =滑块当量>
                    < H5类=拉左>强烈反对和LT; / H5>
                    < H5类=右拉>强烈同意与LT; / H5>
                    &所述;跨度的id =q_@Html.DisplayFor(modelItem = GT; item.Id)类=UI-滑块 - 紫色→3&下; /跨度>
                    <输入类型=隐藏ID =question_valueNAME =question_valueVALUE =3/>
                    <输入类型=隐藏ID =questonIdNAME =questonIdVALUE =@ item.Id/>
                           @ *下;跨度类=UI-滑块 - 红> 55℃; /跨度>
                    * @>< / DIV>
            < / DIV>        }
                            }
                        < / DIV>                        < D​​IV CLASS =一步窗格中的数据步=3>
                            @ *< D​​IV CLASS =中心>
                                    < H3类=蓝色打火机>这是一步3'; / H3 GT&;
                                < / DIV> * @
                            @ {
        的foreach(在Model.Skip变种项(10)。取(5))
        {
            < D​​IV CLASS =COL-MD-12>
                < H4> @ Html.DisplayFor(modelItem => item.Title)LT; / H4>
                < D​​IV ID =滑块当量>
                    < H5类=拉左>强烈反对和LT; / H5>
                    < H5类=右拉>强烈同意与LT; / H5>
                    &所述;跨度的id =q_@Html.DisplayFor(modelItem = GT; item.Id)类=UI-滑块 - 紫色→3&下; /跨度>
                    <输入类型=隐藏ID =question_@item.IdNAME =question_@item.IdVALUE =3/>
                    @ *下;跨度类=UI-滑块 - 红> 55℃; /跨度>
                    * @
                < / DIV>
            < / DIV>        }
                            }
                        < / DIV>                        < D​​IV CLASS =一步窗格中的数据步=4>
                            @ *< D​​IV CLASS =中心>
                                    < H3类=蓝色打火机>这是一步4℃; / H3 GT&;
                                < / DIV> * @
                            @ {
        的foreach(在Model.Skip变种项(15)。取(5))
        {
            < D​​IV CLASS =COL-MD-12>
                < H4> @ Html.DisplayFor(modelItem => item.Title)LT; / H4>
                < D​​IV ID =滑块当量>
                    < H5类=拉左>强烈反对和LT; / H5>
                    < H5类=右拉>强烈同意与LT; / H5>
                    &所述;跨度的id =q_@Html.DisplayFor(modelItem = GT; item.Id)类=UI-滑块 - 紫色→3&下; /跨度>
                    <输入类型=隐藏ID =question_@item.IdNAME =question_@item.IdVALUE =3/>
                    @ *下;跨度类=UI-滑块 - 红> 55℃; /跨度>
                    * @
                < / DIV>
            < / DIV>        }
                            }
                        < / DIV>
                    < / DIV>                    &所述;! - /section:plugins/fuelux.wizard.container - >
                < / DIV>                <小时/>
                < D​​IV CLASS =向导行动>
                    < - #section:插件/ fuelux.wizard.buttons - >
                    <按钮式=按钮ID =previous级=BTN btn- preV>
                        < I类=王牌图标发发左箭头>< I&GT /;
                        preV
                    < /按钮>                    <按钮式=按钮ID =下一步级=BTN BTN-成功BTN-下一个@ *数据最后=完成* @>
                        下一个
                        < I类=王牌图标发发右箭头图标上右键>< I&GT /;
                    < /按钮>
                    <按钮ID =完成级=BTN BTN-成功类型=提交>
                        提交
                        < I类=王牌图标发发右箭头图标上右键>< I&GT /;
                    < /按钮>
                    &所述;! - /section:plugins/fuelux.wizard.buttons - >
                < / DIV>                &所述;! - /section:plugins/fuelux.wizard - >
            < / DIV><! - /.widget-main - >
        < / DIV>
    &所述;! - /.widget-body - >
    }
< / DIV>

的HomeController

 使用System.Data.Entity的;
使用System.Linq的;
使用System.Net;
使用的System.Web;
使用System.Web.Mvc;
使用IdentitySample.Models;
使用STRA.Models;
使用System.Collections.Generic;
使用System.Diagnostics程序;
使用系统;
使用Microsoft.AspNet.Identity;
使用Microsoft.AspNet.Identity.EntityFramework;命名空间IdentitySample.Controllers
{
    [授权]
    公共类HomeController的:控制器
    {
        私人ApplicationDbContext DB =新ApplicationDbContext();
        //公众的ActionResult指数()
        公众的ActionResult指数()
        {
            如果(User.IsInRole(管理))
            {
                返回RedirectToAction(指数,仪表盘);
            }
            如果(User.IsInRole(销售顾问))
            {
                返回RedirectToAction(指数,报告);
            }
            //载荷的所有问题
            // VAR问题= db.Questions.Include(S = GT; s.Survey).INCLUDE(C => c.Category);            VAR问题= db.Questions.Include(C => c.Category);
            返回查看(questions.ToList());
            // VAR questionResults = db.QuestionResults.Include(C => c.Question);
            //返回查看(questionResults.ToList());            //视图模型的尝试
            // VAR视图模型=新SurveyViewModels();
            //viewModel.Questions = db.Questions
            // .INCLUDE(I =>)
        }        [HttpPost]
        公众的ActionResult指数(的FormCollection结果)
        {
            清单< QuestionResult>信息=新的List< QuestionResult>();
            QuestionResult newResult =新QuestionResult();
            VAR APPUSER =新ApplicationUserManager(新UserStore< ApplicationUser>(DB));
            ApplicationUser用户= appUser.FindById(User.Identity.GetUserId());
            的foreach(在result.AllKeys.Where(K =&GT VAR键。k.Contains(问题))ToArray的<串GT;())
            {
                字符串[]键= key.Split(新的char [] {'_'},StringSplitOptions.RemoveEmptyEntries);                如果(key.Count()→1)
                {
                    QuestionResult重新=新QuestionResult();
                    re.QuestionScore = Convert.ToInt32(结果[关键]);
                    re.QuestionId = Convert.ToInt32(键[1]);
                    re.User =用户;
                    db.QuestionResults.Add(重);
                }
            }            db.SaveChanges();            的Debug.WriteLine(结果[0]);
            返回查看();
        }    }
}

jQuery UI的滑块插件

  $(#滑盖当量>跨度),CSS({宽度:'100%','浮动':'左',保证金:'均为15px'})。 。每个(函数(){
            //从标记读取初始值,并删除
            VAR值= parseInt函数($(本)的.text(),10);
            $(本).empty()。滑块({
                值:值,
                分:1,
                最大:5,
                范围:MIN,
                动画:真实,
                改变:函数(事件,UI){
                    //alert(ui.value);
                    $(本)。接下来([ID = ^ _问题])VAL(ui.value)。
                    // $(本>).slider(价值观,$ this.data(指数),$ this.val());
                }            });
        });


解决方案

您认为code为创建具有一定的模型没有任何关系表单控件。相反,创建视图模型重新presenting你需要在视图中显示/编辑什么,可以使用强类型的辅助给你2路模型绑定,并发送回您的视图模型。

查看模型

 公共类SurveyVM
{
  公开名单< CategoryVM>分类{搞定;组; }
  //添加你需要显示/编辑调查的任何其他属性(如身份证,职称等)
}公共类CategoryVM
{
  公开名单< QuestionVM>问题{搞定;组; }
  //添加你需要显示/编辑类别的任何其他属性(如身份证,职称等)
}公共类QuestionVM
{
  公众诠释标识{搞定;组; }
  公共字符串名称{搞定;组; }
  公众诠释得分{搞定;组; }
  //不要包含诸如dateCreated会属性,用户等
}

控制器

 公众的ActionResult指数()
{
  SurveyVM模式=新SurveyVM();
  //填充类别和每个类别,填充相关联的问题
  返回查看(模型);
}[HttpPost]
公众的ActionResult指数(SurveyVM模型)
{
  //遍历每个类别和foreach循环类通过每个问题建立你`名单,LT; QuestionResult>`
}

查看

  @model yourAssembly.SurveyVM
@using(Html.BeginForm())
{
  //添加元素SurveyVM的属性(ID,标题等)
  的for(int i = 0; I< Model.Categories.Count;我++)
  {
    < D​​IV CLASS =类别>
      //添加元素为每个CategoryVM的属性(ID,标题等)
      @for(INT J = 0; J< Model.Categories [I] .Questions.Count; J ++)
      {
        < D​​IV CLASS =问题>
          @ Html.HiddenFor(M = GT; m.Categories [I] .Questions [J] .ID)
          @ Html.DisplayFor(M = GT; m.Categories [I] .Questions [J] .title伪)
          @ Html.TextBoxFor(M = GT; m.Categories [I] .Questions [J] .Score)
        < / DIV>
      }
    < / DIV>
  }
  <输入类型=提交... />
}

So I am creating a survey monkey, a Survey Has 4 categories, and each category has 5 questions, the HomeController Index passes on the 20 questions from the Questions entity and each Questions must have a Range Slider with values from one to 5, the form values must be collected into a method in the controller, then accumulated into the QuestionResults table and processed, then they must be passed onto the CategoryResults and each Category, out of the 4, must have an accumulated score, they must then be compared to the CategoryFeedback(which is static) table and display the correct information. The code for my HomeController and it's index is as below.

The main issue that I am having, is that since I am passing on the form values through as a parameter of FormCollection, I am struggling to keep the relationship of a Question belonging to a Category and then passing these all onto the CategoryResult table for processing.

Any help will be greatly appreciated

Models:

Question

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace STRA.Models
{
    public class Question
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string CreatedBy { get; set; }
        public DateTime? DateCreated { get; set; }
        public DateTime? DateModified { get; set; }
        public virtual Category Category { get; set; }
        public int CategoryId { get; set; }
        public virtual ICollection<QuestionResult> QuestionResult { get; set; }
        public virtual ICollection<QuestionFeedback> QuestionFeedback { get; set; }
    }
}

QuestionResult

using IdentitySample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace STRA.Models
{
    public class QuestionResult
    {
        public int Id { get; set; }
        public DateTime? DateCreated { get; set; }
        public DateTime? DateModified { get; set; }
        public int QuestionScore { get; set; }
        //navigation properties
        public virtual ApplicationUser User { get; set; }
        public ICollection<CategoryResult> CategoryResult { get; set; }
        public virtual Question Question { get; set; }
        public int QuestionId { get; set; }
    }
}

CategoryResult

using IdentitySample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace STRA.Models
{
    public class CategoryResult
    {
        public int Id { get; set; }
        public int CategoryScore {get;set;}
        //navigation properties
        public virtual QuestionResult QuestionResult { get; set; }
        public int QuestionResultId { get; set; }

    }
}

Any help will be greatly appreciated. HomeController Index

@model IEnumerable<STRA.Models.Question>
@{
    //ViewBag.Question.Title = "Survey";
    Layout = "~/Views/Shared/_QuizLayout.cshtml";

}

<div class="hr hr-18 hr-double dotted"></div>

<div class="widget-box">
    <div class="widget-header widget-header-blue widget-header-flat">
        <h4 class="widget-title lighter">STRA</h4>

        @*<div class="widget-toolbar">
                <label>
                    <small class="green">
                        <b>Validation</b>
                    </small>

                    <input id="skip-validation" type="checkbox" class="ace ace-switch ace-switch-4" />
                    <span class="lbl middle"></span>
                </label>
            </div>*@
    </div>
    @*"Create","Home"*@
    @using (Html.BeginForm("Create", "Home", FormMethod.Post))
    {
        @Html.AntiForgeryToken()

        <div class="widget-body">
            <div class="widget-main">
                <!-- #section:plugins/fuelux.wizard -->
                <div id="fuelux-wizard-container">
                    <div class="col-md-12 center">
                        <div class="easy-pie-chart percentage" data-percent="25" data-color="#2679b5">
                            @*<span class="percent">20</span>%*@
                        </div>
                    </div>
                    <div style="display:none;">

                        <!-- #section:plugins/fuelux.wizard.steps -->
                        <ul class="steps">
                            <li data-step="1" class="active">
                                <span class="step">1</span>
                                <span class="Question.Title">Validation states</span>
                            </li>

                            <li data-step="2">
                                <span class="step">2</span>
                                <span class="Question.Title">Alerts</span>
                            </li>

                            <li data-step="3">
                                <span class="step">3</span>
                                <span class="Question.Title">Payment Info</span>
                            </li>

                            <li data-step="4">
                                <span class="step">4</span>
                                <span class="Question.Title">Other Info</span>
                            </li>
                        </ul>

                        <!-- /section:plugins/fuelux.wizard.steps -->
                    </div>

                    <hr />

                    <!-- #section:plugins/fuelux.wizard.container -->
                    <div class="step-content pos-rel">


                        <div class="step-pane" data-step="1">
                            @{

        foreach (var item in Model.Take(5))
        {

            <div class="col-md-12">
                <h4>@Html.DisplayFor(modelItem => item.Title)</h4>

                <div id="slider-eq">
                    <h5 class="pull-left">Strongly Disagree</h5>
                    <h5 class="pull-right">Strongly Agree</h5>
                    <span id="q_@Html.DisplayFor(modelItem => item.Id)" class="ui-slider-purple">3</span>
                    <input type="hidden" id="question_@item.Id" name="question_@item.Id" value="3" />
                </div>
            </div>

        }
        //Model.Skip(5);
                            }
                        </div>
                        <div class="step-pane" data-step="2">
                            @*<div class="center">
                                    <h3 class="blue lighter">This is step 2</h3>
                                </div>*@
                            @{
        foreach (var item in Model.Skip(5).Take(5))
        {


            <div class="col-md-12">
                <h4>@Html.DisplayFor(modelItem => item.Title)</h4>
                <div id="slider-eq">
                    <h5 class="pull-left">Strongly Disagree</h5>
                    <h5 class="pull-right">Strongly Agree</h5>
                    <span id="q_@Html.DisplayFor(modelItem => item.Id)" class="ui-slider-purple">3</span>
                    <input type="hidden" id="question_value" name="question_value" value="3" />
                    <input type="hidden" id="questonId" name="questonId" value="@item.Id" />
                           @*<span class="ui-slider-red">55</span>
                    *@></div>
            </div>

        }
                            }
                        </div>

                        <div class="step-pane" data-step="3">
                            @*<div class="center">
                                    <h3 class="blue lighter">This is step 3</h3>
                                </div>*@
                            @{
        foreach (var item in Model.Skip(10).Take(5))
        {


            <div class="col-md-12">
                <h4>@Html.DisplayFor(modelItem => item.Title)</h4>
                <div id="slider-eq">
                    <h5 class="pull-left">Strongly Disagree</h5>
                    <h5 class="pull-right">Strongly Agree</h5>
                    <span id="q_@Html.DisplayFor(modelItem => item.Id)" class="ui-slider-purple">3</span>
                    <input type="hidden" id="question_@item.Id" name="question_@item.Id" value="3" />
                    @*<span class="ui-slider-red">55</span>
                    *@
                </div>
            </div>

        }
                            }
                        </div>

                        <div class="step-pane" data-step="4">
                            @*<div class="center">
                                    <h3 class="blue lighter">This is step 4</h3>
                                </div>*@
                            @{
        foreach (var item in Model.Skip(15).Take(5))
        {


            <div class="col-md-12">
                <h4>@Html.DisplayFor(modelItem => item.Title)</h4>
                <div id="slider-eq">
                    <h5 class="pull-left">Strongly Disagree</h5>
                    <h5 class="pull-right">Strongly Agree</h5>
                    <span id="q_@Html.DisplayFor(modelItem => item.Id)" class="ui-slider-purple">3</span>
                    <input type="hidden" id="question_@item.Id" name="question_@item.Id" value="3" />
                    @*<span class="ui-slider-red">55</span>
                    *@
                </div>
            </div>

        }
                            }
                        </div>
                    </div>

                    <!-- /section:plugins/fuelux.wizard.container -->
                </div>

                <hr />
                <div class="wizard-actions">
                    <!-- #section:plugins/fuelux.wizard.buttons -->
                    <button type="button" id="previous" class="btn btn-prev">
                        <i class="ace-icon fa fa-arrow-left"></i>
                        Prev
                    </button>

                    <button type="button" id="next" class="btn btn-success btn-next" @*data-last="Finish"*@>
                        Next
                        <i class="ace-icon fa fa-arrow-right icon-on-right"></i>
                    </button>
                    <button id="finish" class="btn btn-success" type="submit">
                        Submit
                        <i class="ace-icon fa fa-arrow-right icon-on-right"></i>
                    </button>
                    <!-- /section:plugins/fuelux.wizard.buttons -->
                </div>

                <!-- /section:plugins/fuelux.wizard -->
            </div><!-- /.widget-main -->
        </div>
    <!-- /.widget-body -->
    }
</div>

HomeController

using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using IdentitySample.Models;
using STRA.Models;
using System.Collections.Generic;
using System.Diagnostics;
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace IdentitySample.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        //public ActionResult Index()
        public ActionResult Index()
        {
            if (User.IsInRole("Admin"))
            {
                return RedirectToAction("Index", "Dashboard");
            }
            if (User.IsInRole("Sales Consultant"))
            {
                return RedirectToAction("Index", "Reports");
            }


            //loads all questions in
            //var questions = db.Questions.Include(s => s.Survey).Include(c => c.Category);

            var questions = db.Questions.Include(c => c.Category);
            return View(questions.ToList());
            //var questionResults = db.QuestionResults.Include(c => c.Question);
            //return View(questionResults.ToList());

            //viewmodel attempt
            //var viewModel = new SurveyViewModels();
            //viewModel.Questions = db.Questions
            //    .Include(i =>)
        }

        [HttpPost]
        public ActionResult Index(FormCollection result)
        {
            List<QuestionResult> info = new List<QuestionResult>();
            QuestionResult newResult = new QuestionResult();
            var appUser = new ApplicationUserManager(new UserStore<ApplicationUser>(db));
            ApplicationUser user = appUser.FindById(User.Identity.GetUserId());
            foreach (var key in result.AllKeys.Where(k => k.Contains("question")).ToArray<string>())
            {
                string[] keys = key.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);

                if (key.Count() > 1)
                {
                    QuestionResult re = new QuestionResult();
                    re.QuestionScore = Convert.ToInt32(result[key]);
                    re.QuestionId = Convert.ToInt32(keys[1]);
                    re.User = user;
                    db.QuestionResults.Add(re);
                }
            }

            db.SaveChanges();

            Debug.WriteLine(result[0]);
            return View();
        }

    }
}

jQuery UI Slider Plugin

$("#slider-eq > span").css({ width: '100%', 'float': 'left', margin: '15px' }).each(function () {
            // read initial values from markup and remove that
            var value = parseInt($(this).text(), 10);
            $(this).empty().slider({
                value: value,
                min: 1,
                max: 5,
                range: "min",
                animate: true,
                change: function (event, ui) {
                    //alert(ui.value);
                    $(this).next("[id^=question_]").val(ui.value);
                    //$(this > ).slider("values", $this.data("index"), $this.val());
                }

            });
        });

解决方案

Your view code is creating form controls which have no relationship to your models. Instead create view models representing what you need to display/edit in the view, use strongly typed helpers to give you 2-way model binding and post back your view model.

View models

public class SurveyVM
{
  public List<CategoryVM> Categories { get; set; }
  // add any other properties of Survey you need to display/edit (e.g. ID, Title etc)
}

public class CategoryVM
{
  public List<QuestionVM> Questions { get; set; }
  // add any other properties of Category you need to display/edit (e.g. ID, Title etc)
}

public class QuestionVM
{
  public int Id { get; set; }
  public string Title { get; set; }
  public int Score { get; set; }
  // Do not include properties such as DateCreated, User etc
}

Controller

public ActionResult Index()
{
  SurveyVM model = new SurveyVM();
  // populate the categories and for each category, populate the associated questions
  return View(model);
}

[HttpPost]
public ActionResult Index(SurveyVM model)
{
  // loop through each Category, and foreach category loop through each Question to build your `List<QuestionResult>`
}

View

@model yourAssembly.SurveyVM
@using (Html.BeginForm())
{
  // add elements for properties of SurveyVM (ID, Title etc)
  for(int i = 0; i < Model.Categories.Count; i++)
  {
    <div class="category">
      // add elements for properties of each CategoryVM (ID, Title etc)
      @for (int j = 0; j < Model.Categories[i].Questions.Count; j++)
      {
        <div class="question">
          @Html.HiddenFor(m => m.Categories[i].Questions[j].Id)
          @Html.DisplayFor(m => m.Categories[i].Questions[j].Title)
          @Html.TextBoxFor(m => m.Categories[i].Questions[j].Score)
        </div>
      }
    </div>
  }
  <input type="submit" .../>
}

这篇关于MVC ASP.NET 5实体框架通过范围输入收集表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆