MVC中的TextboxFor未绑定到for循环中的Model

时间:2018-04-03 16:11:45

标签: c# asp.net-mvc

我的Viewmodel(包含许多子模型)是:

public class ViewModel
{
    public IEnumerable<tblQuestion> DemoQuestions { get; set; }
    public IEnumerable<tblQuestion> TechQuestions { get; set; }

    public List<tblAnswer> DemoQ1Answers { get; set; }
    public List<tblAnswer> DemoQ2Answers { get; set; }
    public List<tblAnswer> TechAnswers { get; set; }

    public string selectedAnswerIDforQ1 { get; set; }
    public string selectedAnswerIDforQ2 { get; set; }
}

我的tblAnswer模型如下:

public partial class tblAnswer
{
    public int AnswerID { get; set; }
    public Nullable<int> QuestionID { get; set; }
    public string AnswerDescription { get; set; }
    public string Q1Other { get; set; }
}

这是我的观看代码:

@using (Html.BeginForm("Display", "Questionnaire", FormMethod.Post))
{
    foreach (tblQuestion question in Model.DemoQuestions)
    {
        <p>@question.QuestionDescription</p>
        @for (int i = 0; i < Model.DemoQ1Answers.Count(); i++)
        {
            if (question.QuestionID == 1)
            {
                <div class="col-md-4">
                @Html.RadioButtonFor(m => Model.selectedAnswerIDforQ1, Model.DemoQ1Answers[i].AnswerID)
                @Model.DemoQ1Answers[i].AnswerDescription
                @Html.HiddenFor(m => Model.DemoQ1Answers[i].AnswerID)
                @Html.HiddenFor(m => Model.DemoQ1Answers[i].AnswerDescription)
                @if (Model.DemoQ1Answers[i].AnswerID == 4)
                {
                    @Html.TextBoxFor(m => Model.DemoQ1Answers[i].Q1Other)     
                }
            </div>
            }  
        }
    }
    <input type="submit" value="Submit" />
}

当我按提交时,模型中的文本框值为空。均值mymodel.DemoQ1Answers[3].Q1Other为空。除此之外,所有其他模型值都与视图中的模型值绑定。

这是我的控制者:

[HttpPost]
public ActionResult Display(ViewModel mymodel)
{ 
    foreach (var demoqstns in mymodel.DemoQuestions)
    {
        int AnswerSelected = 0;
        string otherText = null;
        if (qstnID == 1)
        {
            AnswerSelected = Convert.ToInt32(mymodel.selectedAnswerIDforQ1);
            if (AnswerSelected == 4)
            {
                otherText = mymodel.DemoQ1Answers[3].Q1Other;
            }
        }
        else if (qstnID == 2)
        {
            AnswerSelected = Convert.ToInt32(mymodel.selectedAnswerIDforQ2);
        }
    }
}

请帮忙。

1 个答案:

答案 0 :(得分:-2)

您必须使用foreach设置为foreach的循环  对于(var i = 0; i Model.Orders [i] .CustomerID)

对于循环所生成的每个表单元素,索引值i出现在lambda表达式中,使用的是TextBoxFor HtmlHelper,而不是更为通用(且自动的)的DisplayFor和EditorFor。