无效时,将已检查的html表视图发送回客户端

时间:2015-03-17 08:24:12

标签: c# asp.net-mvc asp.net-mvc-5 .net-4.5

当我的Model.State无效时,我想返回带有选中复选框的视图。

您如何更改我的代码?用我的方法可以吗?

查看

       @model ListTest.Models.PeopleListViewModel


    @{
        var hasMoreThanOnePerson = @Model.People.Count > 1;   
    }

    @Html.BeginForm("Save", "Home")
    {

    @Html.ValidationSummary(false)

    <table>
        @foreach (var item in Model.People)
        {
            <tr>
                @if (hasMoreThanOnePerson)
             {
               <td>
               <input type="checkbox" name="SelectedIds" value="@item.PersonId" />
                </td>
              }
              else
              {
                 @Html.Hidden("SelectedIds", item.PersonId)
              }

                <td>
                    <input type="text" value="@item.Name" />
                </td>
            </tr>
        }
    </table>
    <input type="submit" value="Save" />
    }

视图模型

public class PeopleListViewModel
    {
        public PeopleListViewModel()
        {
            SelectedIds = new int[] { };
        }

        [MinLength(1, ErrorMessage = "Minimum one person must be selected!")]
        public int[] SelectedIds { get; set; }

        public List<Person> People { get; set; }
    }

CONTROLLER

public ActionResult Index()
{ 
    var people = new List<Person> {
        new Person { Name = "Horst", PersonId = 10 }, 
        new Person { Name = "Michael", PersonId = 20} 
    };

    return View(new PeopleListViewModel { People = people });
}

[HttpPost]
public ActionResult Save(PeopleListViewModel viewModel)
{

    if (ModelState.IsValid)
    { 

    }

    viewModel.People = new List<Person> { new Person { Name = "Horst", PersonId = 10 }, new Person { Name = "bernarnd", PersonId = 20 } };

    return View("Index", viewModel);
}

1 个答案:

答案 0 :(得分:1)

很少有改变的事情

首先,更改您的People模型以包含IsSelected属性,我们希望取消您的SelectedIds方法

其次,为了从客户端发布数据,我们需要将您的foreach重写为for,以便正确索引字段,我们还会添加一些额外的{ {1}}用于您要保留的属性(因为我们在验证失败时不再重新填充您的模型),您的表格将为:

HiddenFor

最后,如果验证失败,我们不会在您的操作方法中重新分配您的<table> @for (int i = 0; i < Model.People.Count; i++) { <tr> @Html.HiddenFor(m => m.People[i].PersonID) @Html.HiddenFor(m => m.People[i].Name) @if (hasMoreThanOnePerson) { <td> @Html.CheckBoxFor(m => m.People[i].IsSelected) </td> } else { @Html.HiddenFor(m => m.People[i].IsSelected) } <td> <input type="text" value="@Model.People[i].Name" /> </td> </tr> } </table> 列表,只返回传入的模型。如果您想要获取所选人员,请使用代码I&#39 ; ve在下面添加。另外,因为我们不再拥有People,我们可以执行自己的验证:

SelectedIds