简体   繁体   中英

How to pass List<int> in query string to a controller's action in MVC4

In C# I have three objects in my class like:

public class ABC{
public int AgeMin{get;set;}
public int AgeMax{get;set;}
public List<int> MaritalStatuses{get;set;}
}

Now when I pass all these objects values to controller's action via query string which is receiving the object of type ABC, I am passing like this:

&AgeMin=@Model.filter.AgeMin&AgeMax=@Model.filter.AgeMax&MaritalStatuses=@string.Join(",", @Model.filter.MaritalStatuses)

Values of AgeMin and AgeMax are correct but values of List MaritalStatuses are not correct because it is a List. How can I pass this List values to query string ?

将“婚姻状况”更改为“婚姻状况[0]”,“婚姻状况” [1]等

Well cannot test it right now but you can have a better control if you write a function inside your model class to return proper query string or may be have a wrapper over model or even some extension method taking model object and returning query string for it. Like this:

public class TestModel
{
    public int AgeMin { get; set; }
    public int AgeMax { get; set; }
    public List<int> MaritalStatuses { get; set; }

    public string ToQueryString()
    {
        return string.Format("AgeMin={0}&AgeMax={1}&MaritialStatuses={2}", 
                            AgeMin, AgeMax, string.Join(",", MaritalStatuses));
    }
}

Then use it like this:

<a href="@Url.Action("someAction")?@(Model.ToQueryString())">Testing</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM