ASP.NET MVC模型回传错误的列表

3
所以我有一个视图模型:
public class ClientViewModel
{
    public int ClientID { get; set; }
    [Required]
    [DisplayName("Client Name")]
    public string Name { get; set; }
    [Required]
    [DisplayName("Client Surname")]
    public string Surname { get; set; }
}

以下是我使用的视图模型,其中包括用于搜索客户列表的按钮、按名称排序客户的按钮和按姓氏排序客户的按钮:

@model IList<ClientViewModel>

@using (Html.BeginForm("Index", "Client", FormMethod.Post))
{
@Html.AntiForgeryToken()

<div class="form-horizontal">

<div class="form-group">
    <label class="control-label col-md-2">Enter client info:</label>
    <div class="col-md-10">
        <input type="text" id="clientInfo" name="clientInfo" value="@Session["input"]" />
    </div>
</div>

<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" name="command" value="Search Client" class="btn btn-default" />
    </div>
</div>

<div class="form-group">
    <div class="col-md-offset-2 col-md-2">
        <input type="submit" name="command" value="Sort by client name" class="btn btn-default" />
    </div>
    <div class="col-md-2">
        <input type="submit" name="command" value="Sort by client surname" class="btn btn-default" />
    </div>
</div>

</div>

<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model[0].Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model[0].Surname)
    </th>
</tr>

@for (var i = 0; i < Model.Count; i++)
{
    @Html.HiddenFor(x => x[i].ClientID)
    <tr>
        <td>
            @Html.HiddenFor(x => x[i].Name)
            @Html.DisplayFor(x => x[i].Name)
        </td>
        <td>
            @Html.HiddenFor(x => x[i].Surname)
            @Html.DisplayFor(x => x[i].Surname)
        </td>
        <td>
            @Html.ActionLink("Delete Client", "DeleteClient", new { id = Model[i].ClientID }, new { @class = "btn btn-danger" })
        </td>
        <td>
            @Html.ActionLink("Edit Client", "EditClient", new { id = Model[i].ClientID }, new { @class = "btn btn-default" })
        </td>
    </tr>
}

</table>
}

假设最初的客户端为:

Name       Surname
Adam       Gnb
Brandon    Cook
Kevin      Ginger
Patrick    Star

现在,当我在客户端信息输入框中输入"g"并单击搜索按钮时,它会正确显示使用我输入的关键字的客户端。输出结果如下:

Name      Surname
Adam      Gnb
Kevin     Ginger

现在当我点击“按客户姓氏排序”时,期望的输出结果是:
Name      Surname
Kevin     Ginger
Adam      Gnb

但是post方法中的clients参数出现了一些问题,它保存了"Adam Gnb"和"Brandon Cook"这两个客户端。这就是为什么输出结果会是:

Name      Surname
Brandon   Cook
Adam      Gnb

似乎从视图返回的IList没有保存当前显示的客户端。不知道该如何解决。

编辑1:

过滤方法:

public IEnumerable<ClientDTO> GetByClientInfo(string info)
    {
        if (info.Trim() == "")
            throw new ValidationException("Set the input textbox.", "");
        var mapper = new MapperConfiguration(cfg => cfg.CreateMap<Client, ClientDTO>()).CreateMapper();
        return mapper.Map<IEnumerable<Client>, List<ClientDTO>>(Database.Clients.Find(x => x.Name.ToLower().Contains(info.ToLower()) || x.Surname.ToLower().Contains(info.ToLower())));
    }

排序方法:

public IEnumerable<ClientDTO> SortBySurname(IEnumerable<ClientDTO> clients)
    {
        if (clients == null)
            throw new ValidationException("The client list is empty", "");

        var sortedClients = from client in clients
                            orderby client.Surname
                            select client;

        return sortedClients;
    }

POST方法:

[HttpPost]
    public ActionResult Index(IList<ClientViewModel> clients, string command, string clientInfo)
    {
        if(command.Equals("Sort by client name"))
        {
            var mapper = new MapperConfiguration(cfg => cfg.CreateMap<ClientViewModel, ClientDTO>()).CreateMapper();
            var mapperReverse = new MapperConfiguration(cfg => cfg.CreateMap<ClientDTO, ClientViewModel>()).CreateMapper();

            var sortedClients = clientService.SortByName(mapper.Map<IList<ClientViewModel>, List<ClientDTO>>(clients));
            var afterMap = mapperReverse.Map<IEnumerable<ClientDTO>, IList<ClientViewModel>>(sortedClients);
            return View("Index", afterMap);
        }
        else if(command.Equals("Sort by client surname"))
        {
            var mapper = new MapperConfiguration(cfg => cfg.CreateMap<ClientViewModel, ClientDTO>()).CreateMapper();
            var mapperReverse = new MapperConfiguration(cfg => cfg.CreateMap<ClientDTO, ClientViewModel>()).CreateMapper();

            var sortedClients = clientService.SortBySurname(mapper.Map<IList<ClientViewModel>, List<ClientDTO>>(clients));
            var afterMap = mapperReverse.Map<IEnumerable<ClientDTO>, IList<ClientViewModel>>(sortedClients);
            return View("Index", afterMap);
        }
        else
        {
            Session["input"] = clientInfo;
            IEnumerable<ClientDTO> clientDtos;
            try
            {
                clientDtos = clientService.GetByClientInfo(clientInfo);
                var mapper = new MapperConfiguration(cfg => cfg.CreateMap<ClientDTO, ClientViewModel>()).CreateMapper();
                var resultClients = mapper.Map<IEnumerable<ClientDTO>, IList<ClientViewModel>>(clientDtos);
                return View("Index", resultClients);
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex.Message;
                if (clients == null)
                {
                    return View(new List<ClientViewModel>());
                }
                return View("Index", clients);
            }
        }
    }

你能展示一下进行筛选和排序的方法吗? - Nilesh
请提供需要翻译的内容。 - Desperate Man
你到底在这里干什么?你的视图中没有包含隐藏输入并且没有将模型传回服务器——你根本没有编辑任何东西!你需要再次从数据库获取数据。而且,由于你只是对现有数据进行排序,所以你完全可以在客户端完成所有这些操作。 - user3559349
1个回答

1

请看这个链接

尝试更改您的隐藏输入,不使用Html辅助程序。因为它会将帖子值绑定回输入控件。而是使用普通的HTML元素,如下所示

@for (var i = 0; i < Model.Count; i++)
{
    <input type="hidden" name="[@(i)].ClientId" value="@(Model[i].ClientId)" />
    <tr>
        <td>
            <input type="hidden" name="[@(i)].Name" value="@(Model[i].Name)" />
            @Html.DisplayFor(x => x[i].Name)
         </td>
         <td>
             <input type="hidden" name="[@(i)].Surname" value="@(Model[i].Surname)" />
             @Html.DisplayFor(x => x[i].Surname)
         </td>
         <td>
             @Html.ActionLink("Delete Client", "DeleteClient", new { id = Model[i].ClientID }, new { @class = "btn btn-danger" })
          </td>
          <td>
              @Html.ActionLink("Edit Client", "EditClient", new { id = Model[i].ClientID }, new { @class = "btn btn-default" })
          </td>
    </tr>
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接