5

我正在尝试对我的结果页面进行排序(这是在过滤页面之外的另一个视图中)。我遇到了这个奇怪的问题,我不明白为什么不断发生在我身上。

所有以非常短的形式提供的代码,如果您需要我的代码的任何其他部分以获取更多信息,请询问我。

我的索引视图(用户过滤结果的地方):

@model IEnumerable<Cars.Models.CarSearch>
@using (Html.BeginForm("SearchResult", "Home", FormMethod.Post,
    new
    {
        id = "CategoryFormID",
        data_modelListAction = @Url.Action("ModelList"),
        data_makeListAction = @Url.Action("MakeList"),
        data_editionListAction = @Url.Action("EditionList")
    }))
{
<label>Make</label>
<select id="MakeID" name="carMake">
    <option>All Makes</option>
</select>
}

我的搜索结果视图:

@model IEnumerable<Cars.Models.Car>

<a href="@Url.Action("SearchResult", "Home", new { sortOrder= "Make", filters = ViewBag.CurrentFilters})">Make</a>

我的模型:

public class Car
{
    public String Make { get; set; }      //is my table model
}

public class CarFilter {
    public String carMake { get; set; }
}

public class CarSearch {
    public CarFilter CarFilter { get; set; }
    public byte PageSize { get; set; }
    public short PageNumber { get; set; }
    public int TotalRows { get; set; }
}

我的控制器:

public ActionResult SearchResult(String sortOrder, CarFilter filters)
    {
        ViewBag.CurrentFilters = filters;

        return View();
    }

我要做的就是从 Index 获取 carMake 以 CarFilter 形式将其发布到控制器(因为在我的代码中,表单中有很多字段,我不想把它们全部写下来)当用户点击排序方式 Make it GET SearchResult 方法,它应该设置filters = ViewBag.CurrentFilters用户从一开始输入的值。

Now the funny part is, when I replace CarFilter filters with String carMake and other places respectively. It works like a charm.

My question:

  • Why?

  • How can I do this with CarFilter filters?

UPDATE:

Problem is that filters = ViewBag.CurrentFilters in my SearchResult view does not work with the type CarFilter, because it keeps giving me NULL value when user clicked on the sort by Make.

Second UPDATE:

I tried changing filters = ViewBag.CurrentFilters with CarFilter = ViewBag.CurrentFilters. Now CarFilter filters in my SearchResult(...)method in my controller is not and null object, but ALL the values of the objects in the model class is null (which shouldn't be). I mean the filters object exists but it seems like the values of CarFilter class in my model haven't been passed by ViewBag.CurrentFilters to the view.

4

1 回答 1

0

when you canged the name it worked because framework found property name and the bind it to what you have within action parameters doesnt work so nicely with objects. My advice is to stick with simple types

Here is similiar case: How to send model object in Html.RenderAction (MVC3)

Its not a ViewBag problem thants how it works in general. Its the prime reason for using flatted models :/

于 2012-12-05T15:04:28.937 回答