2015-04-15 83 views
0

所以,我從控制器發送字典對象到我的視圖。如何將Dictionary對象保存到MVC 4中的數據庫?

// GET: QuestionResponses/Create 
    public ActionResult Create(int questionnaireUID) 
    { 
     var questions = from q in db.QUESTIONS 
         where q.QuestionnaireUID == questionnaireUID 
         select q; 


     ViewBag.NextQuestion = from q in db.QUESTIONS 
           where q.QuestionnaireUID == questionnaireUID 
           select new SelectListItem 
           { 
            Selected = (q.QuestionnaireUID == questionnaireUID), 
            Text = q.Question1, 
            Value = q.QuestionUID.ToString() 
           }; 

     Dictionary<QUESTION, QUESTION_RESPONSES> dict = new Dictionary<QUESTION, QUESTION_RESPONSES>(); 

     foreach (var question in questions) 
     { 
      dict.Add(question, new QUESTION_RESPONSES { QuestionUID = question.QuestionUID, Response = "", NextQuestion = "" }); 
     } 

     return View(dict); 
    } 

背後的原因是我需要查看一個模型的數據,並需要添加/編輯另一個模型的數據。我嘗試過使用元組,並且無法實現它(如果你能告訴我怎麼用元組來做到這一點,那也會有所幫助)。

這是視圖對此Dictionary對象的作用。

  <div class="form-group"> 
       <h2> Reponses </h2> 
       <p> For each question, enter in the appropriate response(s). All questions must have at least one response. <p> 
        <div id="editorRows"> 
         <div class="rows_no_scroll"> 
          @foreach (var item in Model.ToArray()) 
          { 

           <!-- The question that responses are being added to. --> 
           Html.RenderPartial("QuestionRow", item.Key); 

           <!-- All questions pertaining to this questionnaire. --> 
           // <p>Please select the question which should be asked as a response to this question.</p> 
           @Html.DropDownList("NextQuestion", null, htmlAttributes: new { @class = "form-control", id = "ddl_questions_" + count}) 
           @Html.ValidationMessageFor(model => item.Value.NextQuestion, "", new { @class = "text-danger" }) 

           <!-- The next question link and responses being inputted by user. --> 
           Html.RenderPartial("ResponseEditorRow", item.Value); 

           // <p> Question @count </p> 
           count += 1; 
          } 
         </div> <!--/rows_no_scroll--> 
       </div> <!-- /editorRows --> 
      </div> <!-- /form-group --> 

爲了完整起見,以下是部分視圖正在做的事情。

QuestionRow:

<div class="questionRow"> 

    <!-- Hide attribute(s) not being viewed/edited. --> 
    @Html.HiddenFor(model => model.QuestionUID) 
    @Html.HiddenFor(model => model.QuestionnaireUID) 

    <!-- Show attribute(s) being viewed. --> 
    @Html.DisplayFor(model => model.Question1) 

    <div class="addQuestion"><a href="" class="addItemResponse" name="addRow[]">Add Response</a></div> 

</div> 

ResponseEditorRow:

<div class="editorRow"> 
    @using (Html.BeginCollectionItem("questions")) 
    { 
     <!-- Hide attribute(s) not being viewed/edited. --> 
     @Html.HiddenFor(model => model.ResponseUID) 
     @Html.HiddenFor(model => model.QuestionUID) 

     <br> 

     <!-- Display attribute(s) being edited. --> 
     @Html.EditorFor(model => model.Response, new { htmlAttributes = new { @type = "text", @name = "question", @class = "question_input" } }) 
     @Html.ValidationMessageFor(model => model.Response, "", new { @class = "text-danger" }) 

     <input type="button" name="addRow[]" class="deleteRow" value="Delete"> 
    } 
</div> 

是我遇到的問題是,當我回到我的控制器發表用戶插入的數據,我的字典是空的。我不確定我是否正確插入信息。我改變了字典對象的toArray(),不知道這是什麼影響......

這裏是HTTP POST創建方法:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create([Bind(Include = "ResponseUID, QuestionUID, Response, NextQuestion")] Dictionary<QUESTION, QUESTION_RESPONSES> question_question_response) 
    { 
     if (ModelState.IsValid) 
     { 

      foreach (var item in question_question_response.ToArray()) 
      { 
       db.QUESTION_RESPONSES.Add(item.Value); 
       db.SaveChanges(); 
       return RedirectToAction("Index"); // Update to take user to Actions/Create page. 
      } 
     } 

     ViewBag.NextQuestion = new SelectList(db.QUESTIONS, "QuestionUID", "Question1"); 
     return View(question_question_response); 
    } 

打開方式的不同,我可以做到這一點的任何建議或者我目前正在做什麼可能是錯誤的。

+1

我認爲做一個ViewModel會更好, –

+0

什麼都不會綁定,因爲你的生成控件的名稱屬性與你的模型沒有任何關係。使用具有'Question'和'Responses'屬性的視圖模型,並使用'EditorTemplates'作爲類型。 –

回答

0

創建2周的ViewModels:

public class QuestionAireViewModel { 

public int QuestionAireId {get;set;} 

public List<QuestionViewModel> Quesitons {get;set;} 

} 


public class QuestionViewModel{ 

public int QuestionId {get;set;} 

public string Question {get;set;} 

public string QuestionResponse {get;set;} 

} 

您認爲通過這QuestionAireViewModel

在控制器中這樣生成QuestionAireViewModel

public ActionResult GetQuestions(int id) 
    { 
    var questionAire = db.QuesitonAire.First(s => s.QuestionAireId == id) 

    var questions = new List<QuestionViewModel>(); 

    foreach(var question in questionAire.Questions){ 

    questions.Add(new QuestionViewModel(){ 
    Quesiton = question.Question, 
    }); 

    } 


    var model = new QuestionAireViewModel(){ 
    QuestionAireId = questionAire.Id, 
    Quesitons = questions 
    }; 

return View(model); 

    } 

然後在POST形式方法是:

[HttpPost] 
public ActionResult SaveQuestions(QuestionAireViewModel model) 
{ 

} 
相關問題