集合过滤(将列表<string>传递给View并返回控制器)</string>

时间:2013-02-11 19:21:42

标签: asp.net-mvc json razor variable-assignment

我正在为我收集的一个集合编写增强的搜索功能,而且我遇到了一个问题。我正在尝试将List存储在表单中的隐藏字段中,以便每次用户发布表单时都可以添加List。

这是我的控制器代码:

public ActionResult Index(Int32 page = 0, List<String> filters = null, String filter = "", Int32 pageSize = 10, Boolean sortAscending = true, String sortBy = "Title") {
    UserContext uc = SecurityHelpers.GetUserData();
    LinkedList<SongViewModel> svm = new LinkedList<SongViewModel>();

    var songs = _songRepository.FindAll()
                               .Where(a => a.Title.Contains(filter) ||
                                           a.Lyrics.Contains(filter) ||
                                           a.Description.Contains(filter));

    ViewBag.ResultsCount = songs.Count();
    ViewBag.Page = page;
    ViewBag.PageSize = pageSize;
    ViewBag.SortAscending = sortAscending;

    if (filters == null) {
        filters = new List<String>();
    }
    filters.Add(filter);
    ViewBag.Filters = new JavaScriptSerializer().Serialize(filters);

    songs = songs.Sort(sortBy, sortAscending)
                 .Skip(page * pageSize)
                 .Take(pageSize);

    foreach (Song s in songs) {
        ((LinkedList<SongViewModel>)svm).AddLast(new SongViewModel(uc.SongWriterId) {
            Song = s
        });
    }
    return View("songs", svm);
}

这是我的观看代码:

<li>
    <input type="text" class="textbox" name="filter" />
    <input type="hidden" value="@ViewBag.Filters" name="filters" />
</li>

当我提交表单时,一切似乎都有效,但ViewBag.Filters现在包含一个列表列表?

  • “索引”操作的第一次运行在隐藏字段中显示“过滤器”的值[“”]。
  • 如果我为过滤器提交'asdf'值,我会得到[“[\”\“]”,“asdf”]。
  • 如果我再次提交值为'foo'的过滤器,我会得到[“[\”[\\“\\”] \“,\”asdf \“]”,“foo”]。

有没有人对我做错了什么有任何想法?似乎Json解析器将过滤器的值解释为列表中的单个元素,我只是不知道如何解决这个问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案!

如果我将列表转换为CSV字符串,模型绑定器会正确解释它。

ViewBag.Filters = filters.Aggregate("", (s, x) => string.IsNullOrEmpty(s) ? x : s + ", " + x);