문제

This is the query string that Datatables.net sends to my MVC action:

?sEcho=8&iColumns=6&sColumns=&iDisplayStart=0&iDisplayLength=10&mDataProp_0=HomeCountry&mDataProp_1=HostCountry&mDataProp_2=YearOneRate&mDataProp_3=YearOtherRate&mDataProp_4=RateType&mDataProp_5=Controls&sSearch=&bRegex=false&sSearch_0=&bRegex_0=false&bSearchable_0=true&sSearch_1=&bRegex_1=false&bSearchable_1=true&sSearch_2=&bRegex_2=false&bSearchable_2=true&sSearch_3=&bRegex_3=false&bSearchable_3=true&sSearch_4=&bRegex_4=false&bSearchable_4=true&sSearch_5=&bRegex_5=false&bSearchable_5=true&iSortCol_0=1&sSortDir_0=asc&iSortingCols=1&bSortable_0=true&bSortable_1=true&bSortable_2=true&bSortable_3=true&bSortable_4=true&bSortable_5=false&_=1391446190711

This is my controller action header in MVC:

public JsonResult GetData(int sEcho, int iDisplayStart, int iDisplayLength, string sSearch)

My question is: How do I get variables such as these (?):

bSortable_0=true&bSortable_1=true&bSortable_2=true&bSortable_3=true&bSortable_4=true&bSortable_5=false

Notice how the number after bSortable_ could be anything from 0 to 5 or more.

도움이 되었습니까?

해결책

To parse querystring -

NameValueCollection queryCollection = HttpUtility.ParseQueryString(Request.Url.Query);
var items = queryCollection
                 .AllKeys
                 .SelectMany(queryCollection.GetValues, (k, v) => new { key = k, value = v })
                 .Where(p => p.key.Contains("bSortable"))
                 .ToList();

And the output -

enter image description here

다른 팁

You can get all the query string parameters from the Request.QueryString collection, including the ones you didn't make method parameters. You can find the individual keys in Request.QueryString.Keys. Using that, you could loop through the collection and grab each key/value pair.

There are a couple other ways. You could do:

string bSearchable0 = Request["bSearchable_0"];

Or you could make a class and have your action method take it as a parameter:

public class jQueryDataTableParam
{
    public int sEcho { get; set; }
    public int iDisplayStart { get; set; } 
    public int iDisplayLength { get; set; } 
    public string sSearch { get; set; }
    public bool bSearchable_1 { get; set; }
    public bool bSortable_1 { get; set; }
    //....
}

Using the above make your action method look more like

public JsonResult GetData(jQueryDataTableParam param)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top