Why the only hidden field that is being filled from GET action is not being passed in model?

Posted by user1807954 on Stack Overflow See other posts from Stack Overflow or by user1807954
Published on 2012-12-07T04:00:14Z Indexed on 2012/12/07 5:04 UTC
Read the original article Hit count: 145

Filed under:
|
|

Sorry for the long title, I didn't know how to make it any shorter.

  • My code:

My model:

public class CarFilter {
    public String carMake { get; set; }
    public String carModel { get; set; }
    public String carEdition { get; set; }
    .
    .
    .
    public String SortBy { get; set; }
}

public class CarSearch : CarFilter {
    public List<Car> Car { get; set; }
}

My controller:

public ActionResult SearchResult(CarSearch search)
    {
        var cars = from d in db.Cars
                   select d;

        if (Request.HttpMethod == "POST")
        {
            search.SortBy = "Price";
        }
        search.Car = new List<Car>();
        search.Car.AddRange(cars);

        var temp = new List<CarSearch>();
        temp.Add(search);

        return View(temp);
}

My Index view (where user filters results):

@model IEnumerable<Cars.Models.CarSearch>
@using (Html.BeginForm("SearchResult", "Home", FormMethod.Post)){..forms and other stuff..}

My SearchResult view (where user sees the results of filtration):

@model IEnumerable<Cars.Models.CarSearch>
@using (Html.BeginForm("SearchResult", "Home", FormMethod.Get))
{
@Html.Hidden("carMake")
@Html.Hidden("carModel")
@Html.Hidden("carEdition")
.
.
.
@Html.Hidden("SortBy", temp.SortBy)

<input name="SortBy" class="buttons" type="submit" value="Make"/>
  • My goal

What I'm trying to do is when user clicked on sort by Make it will have to GET back all the variables in hidden field back to the SearchResult action in order to sort the result (same filtered results).

  • Result

Is: <input id="SortBy" name="SortBy" type="hidden" value=""/>. The value is null and it's not being passed but all the other hidden fields such as carMake and etc have value. But when I use foreach it works perfect.

  • Question

Why is this like this? the SortBy is in the same model class as other fields in the view. The only difference is that SortBy is not being filled in the Index view with other fields, instead it's being filled in controller action. What is the explanation for this? Am I missing any C# definition or something such as dynamic objects or something?

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc-3