【问题标题】:send a list to view,fill and get it in asp.net mvc发送列表以查看,填写并在 asp.net mvc 中获取
【发布时间】:2016-07-09 16:16:49
【问题描述】:

我有一个测验表格,它显示了一些问题及其答案(单选按钮), 用户必须回答问题并发送, 我做了一些这样的课:

  public class Question 
{

    public int Qid { get; set; }
    public string Questionstext { get; set; }
    public int selected { get; set; }
    public List<Qitem> lst { get; set; }

}
public class Qitem
{
    public int id { get; set; }
    public string txt { get; set; }

}

然后我将问题列表发送到视图中:

 List<Question> llst = new List<Question>
        {
            new Question
            {
                Qid = 1,
                Questionstext = "is it true?",
                lst = new List<Qitem>
                {
                    new Qitem
                    {
                        txt = "yes",
                        id = 1
                    },
                    new Qitem
                    {
                        id = 2,
                        txt = "no"
                    }
                }
            },
            new Question
            {
                Qid = 1,
                Questionstext = "is it true 2?",
                lst = new List<Qitem>
                {
                    new Qitem
                    {
                        txt = "yes2",
                        id = 3
                    },
                    new Qitem
                    {
                        id = 4,
                        txt = "yes3"
                    }
                }
            }
        };

        return View(llst);

我怎样才能显示它然后提交答案, 答案必须放在问题的“选定”属性中。 我的问题是关于视图和特别是单选按钮。

【问题讨论】:

    标签: c# asp.net-mvc radio-button


    【解决方案1】:

    你的观点应该是

    @model List<Question>
    @using (Html.BeginForm())
    {
        for (int i = 0; i < Model.Count; i++)
        {
            @Html.HiddenFor(m => m[i].Qid)
            <h2>@Model[i].Questionstext</h2>
            foreach (var answer in Model[i].lst)
            {
                <label>
                    @Html.RadioButtonFor(m => m[i].selected, answer.id, new { id = "" })
                    <span>@answer.txt </span>
                </label>
            } 
        }
        <input type="submit" value="Save" />
    }
    

    将回发到(假设Index 与用于生成此视图的 GET 方法同名)。

    public ActionResult Index(List<Question> model)
    

    附注:如果您还希望发布 Questionstext 值,请包括 @Html.HiddenFor(m =&gt; m[i].Questionstext)

    【讨论】:

    • 如果我们向视图发送多个不同模型的列表,我们也可以使用 Viewbag 或 tempdata 来存储列表并在视图中使用
    • @HimaanSingh, TempData 不适合将数据发送到视图,并且建议 ViewBag 代替 OP 正在做的强类型模型是非常实用的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多