【问题标题】:Get data from Form in MVC3?从 MVC3 中的表单获取数据?
【发布时间】:2012-05-09 17:51:19
【问题描述】:

我有这个视图用于呈现表单

@using ExpertApplication.ViewModels
@model IEnumerable<QuestionViewModel>
@{
    ViewBag.Title = "GetQuestions";
}
@using(Html.BeginForm("ProcessAnswers", "Home", FormMethod.Post))
{
    foreach(QuestionViewModel questionViewModel in Model)
    {
        Html.RenderPartial("QuestionPartialView", questionViewModel);
    }
<input type="submit" value="Send data"/>
}
}
<h2>GetQuestions</h2>

和局部视图

@using ExpertApplication.ViewModels
@model QuestionViewModel
<div id="question">
    @Model.Text
    <br />
    <div id="answer">
        @foreach(var answer in Model.AnswerViewModels)
        {
            @(Model.IsMultiSelected
            ? Html.CheckBoxFor(a => answer.Checked)
            : Html.RadioButtonFor(a => answer.Checked, false))
            @Html.LabelFor(a => answer.Text)
            <br />
        }
    </div>
</div>

我想从 From 获取数据

[HttpPost]
public ActionResult ProcessAnswers(IEnumerable<QuestionViewModel> answerForQuesiton)
{
//answerForQuestion always is null
}

但参数 answerForQuesiton 为空。如何解决这个问题?

【问题讨论】:

    标签: asp.net-mvc-3 forms ienumerable


    【解决方案1】:

    MVC 使用零索引名称绑定列表。不幸的是,由于这个原因,虽然foreach 循环将创建包含正确值的输入,但它们不会创建使用正确名称的输入名称。因此,您不能使用foreach 绑定列表

    例如:

    for (int i = 0; i< Model.Foo.Count(); i++)
    {
        for (int j = 0; j < Model.Foo[i].Bar.Count(); j++)
        {
            @Html.TextBoxFor(m => m.Foo[i].Bar[j].myValue)
        }
    }
    

    将创建名称如“Foo[1].Bar[2].myValue”的文本框并正确绑定。然而,

    foreach (var foo in Model.Foo)
    {
        foreach (var bar in foo.Bar)
        {
            @Html.TextBoxFor(m => bar.myVal);
        }   
    }
    

    将创建具有与前一个循环完全相同的值的文本框,但它们都将具有“name="bar.myVal”,因此它们都不能绑定。

    所以要解决您的问题:
    1)你可以用 for 循环替换你的 foreach 循环。注意:这需要使用IListList 而不是IEnumerable
    2) 您可以使用 EditorTemplates 自动为您应用正确的名称。

    【讨论】:

      【解决方案2】:

      您使用了错误的机制。您应该使用 EditorTemplates 而不是部分视图。编辑器模板知道如何处理集合和创建格式正确的名称属性,以便它们可以在回发时绑定。

      http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-11
        • 1970-01-01
        • 2017-05-14
        相关资源
        最近更新 更多