【问题标题】:Passing value from DropDownList to model's list将值从 DropDownList 传递到模型的列表
【发布时间】:2021-07-06 03:17:39
【问题描述】:

所以我有一个使用 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" />
}

正在使用的模型有一个名为 answers 的列表,我正在尝试将创建的每个下拉列表的值传递到模型的列表中。 正在使用的控制器具有以下功能

public void sendTestData(Model model)
{
    //business logic
}

型号:

    public class Model
    {
        public List<string> answers = new List<string>();
    }

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

【问题讨论】:

    标签: c# asp.net entity-framework model-view-controller


    【解决方案1】:

    我可以看到您的模型属性没有正确初始化。

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

    你可以这样写模型属性

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

    更新 -- 一些建议

    我不知道您为什么在 ViewBag 而不是模型上传递问题。也许你有一些理由。但如果是我,我会创建这样的代码

    模型类:

    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
    }
    

    因为我使用 MVC 的原因之一是强类型模型绑定。所以我将在表单处理中使用模型而不是 ViewBag。

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 2015-10-06
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多