2015-06-03 56 views
-1

因此,我創建了一個調查猴子,一個調查有4個類別,每個類別有5個問題,HomeController索引傳遞來自實體的20個問題,每個問題必須有一個範圍滑塊,其值爲1到5,表單值必須收集到控制器中的一個方法中,然後累積到QuestionResults表中並處理,然後它們必須傳遞到CategoryResults和每個Category中, 4,必須有累計分數,然後必須將它們與類別反饋(這是靜態)表進行比較並顯示正確的信息。我的HomeController的代碼和它的索引如下。MVC 5 ASP.NET實體框架通過範圍輸入收集表格數據

我遇到的主要問題是,因爲我通過FormCollection的參數傳遞表單值,所以我努力保持屬於類別的問題的關係,然後將這些全部傳遞到CategoryResult表進行處理。

任何幫助,將不勝感激

型號:

問題

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

    } 
} 

任何幫助將不勝感激。 的HomeController指數

@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="[email protected](modelItem => item.Id)" class="ui-slider-purple">3</span> 
        <input type="hidden" id="[email protected]" name="[email protected]" 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="[email protected](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="[email protected](modelItem => item.Id)" class="ui-slider-purple">3</span> 
        <input type="hidden" id="[email protected]" name="[email protected]" 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="[email protected](modelItem => item.Id)" class="ui-slider-purple">3</span> 
        <input type="hidden" id="[email protected]" name="[email protected]" 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-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()); 
       } 

      }); 
     }); 
+0

這樣,我也許還可以利用一個視圖模型這樣的公共類SurveyViewModels { 公開名單問題{獲得;組; } public List CategoryResult {get;組; } public List QuestionResults {get;組; } public list 類別{get;組; } // public List QuestionFeedbacks {get;組; }} 我 – Mic

+0

理解,但沒有對範圍值@Html幫手,讓我堅持到普通HTML範圍的投入,我需要有相關的範圍內輸入的每個問題,我不太清楚我會如何創建此視圖模型來說實話...感謝您的幫助 – Mic

+0

嘿夥計,說實話,我與它掙扎着,反正是有,你可以提供一點援助的我怎麼會組織我的ViewModel方面?或者,如果你能指出我正確的方向,將不勝感激...謝謝 – Mic

回答

0

我會在你的RazorTemplate增加出題類型爲前綴question_id或question_name這是通過的FormCollection

<input type="hidden" id="@(item.category_id)[email protected]" name="@(item.category_id)[email protected]" value="3" /> 

然後在你的控制器動作什麼來通過,只是從名字開始拉出CATEGORY_ID,讓你知道什麼類別您當前迭代通過。

0

您的視圖代碼正在創建與您的模型無關的表單控件。相反,創建視圖模型來表示需要在視圖中顯示/編輯的內容,使用強類型幫助器爲您提供雙向模型綁定並回發視圖模型。

查看模型

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 
} 

控制器

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

查看

@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" .../> 
} 
+0

第一部分。暫時忘記腳本。需要確保您瞭解如何模型綁定作品首次,而且在任何情況下,有問題你的腳本 - 您有重複的'id'屬性('「滑塊-EQ」'),這是無效的HTML和'$(「#滑塊-eq> span「)'只會選擇第一個。稍後我將更新您如何更正此問題並簡化代碼的其他方面。此外,建議您首先對「SurveyVM」中的某個'CategoryVM'和'QuestionVM'對象進行硬編碼以進行測試。 –

+0

非常感謝,我非常感謝。我將測試它現在 – Mic

+0

嘿夥計,我現在用你的方法,但我在索引視圖接收空異常錯誤,我也試圖通過郵局動作如下[HttpPost] 公衆的ActionResult IndexSurveyViewModel循環通過(SurveyViewModel模型) { //循環遍歷每個類別,並通過每個問題的foreach類循環來建立你的'List ' foreach(var category in model.Categories) { foreach(var category.Questions中的問題) { } } } – Mic