在视图模型上生成一个列表



我想生成列表并绑定到视图模型,但我在下面得到错误,我定义了错误的属性吗?

传入字典的模型项类型为"SurveyTool.Models。AnswerQuestionViewModel',但是这个字典类型的模型项System.Collections.Generic.IEnumerable 1 [SurveyTool.Models.AnswerQuestionViewModel] '。

Edit.cshtml:

@model IEnumerable<SurveyTool.Models.AnswerQuestionViewModel>
@{
    ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<table>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Question)
        </td>
        <td>
            @Html.EditorFor(modelItem => item.Answer)
        </td>
    </tr>
}
</table>

SURV_AnswerController:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SurveyTool.Models;
namespace SurveyTool.Controllers
{
    public class SURV_AnswerController : Controller
    {
        private SurveyToolDB db = new SurveyToolDB();
        //
        // GET: /SURV_Answer/
        public ActionResult Edit(int Survey_ID)
        {
            AnswerQuestionViewModel viewmodel = new AnswerQuestionViewModel();
            var query = from r in db.SURV_Question_Ext_Model
                        join s in db.SURV_Question_Model
                        on r.Qext_Question_ID equals
                        s.Question_ID
                        where s.Question_Survey_ID == Survey_ID
                        orderby s.Question_Position ascending
                        select r;
            foreach(var item in query)
            {
                viewmodel.Question = item.Qext_Text;
            }
            return View(viewmodel);
        }
    }
}

AnswerQuestionViewModel:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SurveyTool.Models
{
    public class AnswerQuestionViewModel
    {
        public string Answer { get; set; }
        public string Question { get; set; }
    }
}

您只返回单个AnswerQuestionViewModel项,而不是集合。在public ActionResult Edit(int Survey_ID)方法中,更改

AnswerQuestionViewModel viewmodel = new AnswerQuestionViewModel();

List<AnswerQuestionViewModel> viewmodel = new List<AnswerQuestionViewModel>();

,然后在foreach循环

foreach(var item in query)
{
    viewmodel.Add(new AnswerQuestionViewModel() { Question = item.Qext_Text });
}
return View(viewmodel);

编辑

注意你的视图也有问题。使用foreach循环会生成重复的name属性,因此在回发时不会绑定集合。由于重复的id属性,它还会生成无效的html。您需要为AnswerQuestionViewModel的类型使用自定义EditorTemplatefor循环。使用for循环,它需要是

@model List<SurveyTool.Models.AnswerQuestionViewModel>
@using (Html.BeginForm())
{
    for(int i = 0; i < Model.Count; i++)
    {
        @Html.DisplayFor(m => m[i].Question)
        @Html.EditorFor(m => m[i].Answer)
    }
    <input type="submit" />
}

然而,这只会发布回模型的Answer属性。您没有任何标识问题ID的属性,因此您可能需要为ID添加一个额外的属性,并在视图

中为其包含一个隐藏输入

相关内容

  • 没有找到相关文章

最新更新