无法将选定的复选框项绑定到模型MVC3

时间:2014-03-19 15:26:49

标签: c# asp.net-mvc-3

我有这类状态:

public class Status
    {
        public Status(int id, string description)
        {
            Id = id;
            Description = description;
        }


        public int  Id { get; set; }
        public string Description { get; set; }
        public bool IsChecked { get; set; }

    }

这是我的模特:

public class StatusModel
{
    public StatusModel()
    {
        Statuses = new List<Status>();
    }
    public List<Status> Statuses { get; set; }

}

我的视图如下所示:

@model MVCTestApplication.Models.StatusModel

@using (Html.BeginForm("TestView", "Home"))
{
 <table>
 <thead>
       <tr>
           <th>
           Status
           </th>
       </tr>
 </thead>

 <tbody>
 @for (int i = 0; i < Model.Statuses.Count(); i++)
 {
 <tr>
 <td>

 @Html.CheckBoxFor(x => x.Statuses[i].IsChecked, new { @id = Model.Statuses[i].Id })

 @Html.LabelFor(x => x.Statuses[i].Description, Model.Statuses[i].Description)

 @Html.HiddenFor(x => x.Statuses[i].Description)

 @Html.HiddenFor(x => x.Statuses[i].Id)

 </td>
 </tr>
 }

</tbody>
</table>

    <input type="submit" name="submit" value="submit" />
}

在控制器中我有:

public ActionResult TestView(StatusModel statuses)
{
//.......
}

我需要选中所有选中的复选框项,但是当我编写这样的代码时,我的控制器中的状态变量为null。我不知道自己做错了什么

1 个答案:

答案 0 :(得分:3)

你必须做这样的事情,从db读取并传递给视图:

public ActionResult TestView()
{
DataTable datatable = ReadStatus("yourconnectionstring");
List<Status> statuses = DataTableToStatus(datatable);
StatusModel model = new StatusModel();

model.Statuses = statuses 
return View(Statuses);
}


private DataTable ReadStatus(string connectionString) 
{ 
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand(); 
cmd.CommandText = @"SELECT * FROM Statuses"; 
da.SelectCommand = cmd; 
DataSet ds = new DataSet(); 
conn.Open(); 
da.Fill(ds); 
conn.Close(); 
return ds.Tables[0]; 
} 

private List<Status> DataTableToStatus(DataTable table) 
{ 
for (int i = 0; i < table.Rows.Count; i++) 
{ 
int id = (int)table.Rows[i].ItemArray[0];
string desc = (string)table.Rows[i].ItemArray[1];
statuses.Add(new Status(id, desc)); 
} 

return statuses; 
}

以下是您将发布数据模型的行动:

[HttpPost]
public ActionResult TestView(ModelStatus model)
{
// your business logic here
}

在视图中设置httpmethod发布:

@using (Html.BeginForm("TestView", "Home",HttpMethod="POST"))
{
 <table>
 <thead>
       <tr>
           <th>
           Status
           </th>
       </tr>
 </thead>

 <tbody>
 @for (int i = 0; i < Model.Statuses.Count(); i++)
 {
 <tr>
 <td>

 @Html.CheckBoxFor(x => x.Statuses[i].IsChecked, new { @id = Model.Statuses[i].Id })

 @Html.LabelFor(x => x.Statuses[i].Description, Model.Statuses[i].Description)

 @Html.HiddenFor(x => x.Statuses[i].Description)

 @Html.HiddenFor(x => x.Statuses[i].Id)

 </td>
 </tr>
 }