在控制器post方法中,MVC 5模型中的提交表单为空

时间:2016-06-17 15:36:05

标签: asp.net-mvc

发帖后,我在模型中获取List为null 我的模型有一个属性,它是vwLog的列表。

public class CreateLogViewModel
{
    public List<vwLog> LogData;
}

在视图中我使用了该模型并使用foreach循环在文本控件中分配值

@model CreateLogViewModel

@using (Html.BeginForm("CreateLog", "Log", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    foreach (var item in Model.LogData)
    {
        <table>            
            <tr>
                <td>
                    @Html.HiddenFor(modelItem => item.LogID)
                    @Html.TextBoxFor(modelItem => item.AgencyBillingCode)
                </td>
                <td>
                    @Html.TextBoxFor(modelItem => item.LicenseNumber)
                </td>
            </tr>
        </table>
    }
    <div class="col-xs-12" align="center">
        <input class="btn btn-default" type="submit" name="Submit" value="Save" id="Submit">
    </div>
}

我的控制器

在Get方法中,我在LogData对象中分配值,该对象是vwlog的集合。

public ActionResult CreateLog(CreateLogViewModel model)
{
   model.LogData = GetDate();
   return View(model);
 }

我在屏幕上更新列表的某些值并尝试保存,但我在Post中获得了model.LogData null。

[HttpPost]
public ActionResult CreateLog(CreateLogViewModel model, string submit)
{
    if (model.LogData != null)
    { 
        do this...
    }
}

我在屏幕上更新列表的某些值并尝试保存,但我在Post中获得了model.LogData null。 model不为null,但collection对象为null。 请让我知道我错在哪里。

1 个答案:

答案 0 :(得分:1)

MVC模型绑定器不适用于类字段:

public class CreateLogViewModel
{
    // This is a field
    public List<vwLog> LogData;
}

必须使用属性:

public class CreateLogViewModel
{
    // This is a property
    public List<vwLog> LogData { get; set; }
}
  

注意:您还需要确保vwLog类型具有公共读写属性才能生效。