Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将值从DropDownList传递到model';s列表_C#_Asp.net_Entity Framework_Model View Controller - Fatal编程技术网

C# 将值从DropDownList传递到model';s列表

C# 将值从DropDownList传递到model';s列表,c#,asp.net,entity-framework,model-view-controller,C#,Asp.net,Entity Framework,Model View Controller,因此,我有一个使用DropDownListFor创建的下拉列表,它显示良好,但数据没有正确发送到控制器 @using (Html.BeginForm("sendTestData", "Dashboard", FormMethod.Post)) { var cnt = 0; foreach (string question in ViewBag.Questions) { <h3>@Html.DisplayF

因此,我有一个使用DropDownListFor创建的下拉列表,它显示良好,但数据没有正确发送到控制器

@using (Html.BeginForm("sendTestData", "Dashboard", FormMethod.Post))
{
    var cnt = 0;
    foreach (string question in ViewBag.Questions)
    {
        <h3>@Html.DisplayFor(x => question)</h3>
        @Html.DropDownListFor(x => x.answers[cnt], new SelectList(ViewBag.Answers))
        cnt++;
    }
    <input id="Submit" type="submit" value="submit" />
}
模型:

    public class Model
    {
        public List<string> answers = new List<string>();
    }
公共类模型
{
公共列表答案=新列表();
}

我检查了列表的值:model.answers,它只是一个空列表,没有数据放入其中。

我看到的是,您的模型属性没有正确初始化

如果这样编写模型属性,那么答案将像变量一样工作,因为它们只是初始化数据(列表字符串),而不是从视图接收数据

您可以这样编写模型属性

public class Model
{
    public List<string> answers { get; set; }

    public Model(){
        answers = new List<string>();
    }
}
因为我使用MVC的原因之一是强类型模型绑定。所以我将在表单处理中使用模型,而不是ViewBag

public class Model
{
    public List<string> answers { get; set; }

    public Model(){
        answers = new List<string>();
    }
}
public class Question
{
    public string Question { get; set; }
    public List<string> AnswerList { get; set; }
    public string AnswerSelected { get; set; }
}

public class MainModel
{
    public List<Question> QuestionList
}
@model ...MainModel

@using (Html.BeginForm("sendTestData", "Dashboard", FormMethod.Post))
{
    var cnt = 0;
    foreach (string question in Model.QuestionList)
    {
        <h3>@Html.DisplayFor(x => x.QuestionList.Question)</h3>
        @Html.DropDownListFor(x => x.QuestionList.AnswerSelected , new SelectList(Model.AnswerList))
        cnt++;
    }
    <input id="Submit" type="submit" value="submit" />
}
public void sendTestData(MainModel model)
{
    //business logic
    //Loop through QuestionList
}