简体   繁体   English

如何通过名单 <int> 在查询字符串中到MVC4中控制器的操作

[英]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: 在C#中,类中有三个对象,例如:

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: 现在,当我通过接收ABC类型对象的查询字符串将所有这些对象值传递给控制器​​的操作时,我将像这样传递:

&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. AgeMin和AgeMax的值正确,但是List MaritalStatuses的值不正确,因为它是一个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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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