I don't know how to phrase this question properly but basically I haven an ASP.Net Application. I send the following request to the controller from my view:
http://localhost:59112/Contacts/IndexJson?current=1&rowCount=50&sort%5BLastName%5D=desc&searchPhrase=&_=1490960196673
I have written two classes that are not working 100% as follows for a structure for this request data:
public class RequestData
{
public int current { get; set; }
public int rowCount { get; set; }
public string searchPhrase { get; set; }
public IEnumerable<SortData> sortItems { get; set; }
}
public class SortData
{
public string Field { get; set; } // FIeld Name
public string Type { get; set; } // ASC or DESC
}
Then in my controller I have the following:
public JsonResult IndexJson(RequestData model)
{
/* Irrelevant code */
}
The model works and fills everything correctly except the sortItems
returns null. How can I get the sortItems
Field
and Type
defined in my class?
Since the parameter coming in from the RequestData
is sort[Field]=Type
.
I changed my RequestData
class to this:
public class RequestData
{
public int current { get; set; }
public int rowCount { get; set; }
public Dictionary<string, string> sort { get; set; }
public string searchPhrase { get; set; }
public Guid id { get; set; }
}
Now the model
holds the sort
as {[Field, Type]}
(an example of data).
If this is a good practice, how to I access Field
and Type
?
You can achieve this a number of different ways; your problem in each case was simply not following the modelbinder conventions for that data type.
First and foremost, IEnumerable
is out if you intend to post back to it. It's not an indexable type, so the modelbinder will never be able to bind to it. However, using something like List
instead, is just fine. Then, your param names simply need to be in the format of: ListProperty[N].Property
, where N
is the index. So for your situation you could have used sortItems[0].Field=LastName&sortItems[0].Type=desc
, and it would have bound just fine to your model.
For using a dictionary, your names should be in the format of DictionaryProperty[N].Key
and DictionaryProperty[N].Value
, where again, N
is the index. In your scenarion that would look like sort[0].Key=LastName&sort[0].Value=desc
.