如何在MVC 4中将Dictionary对象保存到数据库?

时间:2015-04-15 13:18:15

标签: asp.net-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);
    }

这背后的原因是我需要查看一个模型的数据,并需要添加/编辑另一个模型的数据。我尝试使用Tuples并且无法使它工作(如果你能告诉我如何用元组做这个,那也会有帮助。)

这是视图对此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>

我遇到的问题是,当我回到我的控制器POST用户插入的数据时,我的字典为空。我不确定我是否正确插入信息。我正在将字典对象更改为Array(),不确定这是否会影响任何内容......

这是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 个答案:

答案 0 :(得分: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 Form上的方法是:

[HttpPost]
public ActionResult SaveQuestions(QuestionAireViewModel model)
{

}