htiru htiru - 1 month ago 10
Ajax Question

pass complex data to get call if api

I am trying to pass a viewmodel data to get call in web api..

here is the viewmodel properties

public class FilterViewModel
{
public int RegionID { get; set; }

public int StateID { get; set; }

public int DistrictID { get; set; }

public int UniversityID { get; set; }

public int CollegeID { get; set; }

public DateTime FromDate { get; set; }

public DateTime ToDate { get; set; }
}


here is the ajaxcall that i am trying to ..


to convert formdata to json object


function toSimpleJson() {

});
return json;
}



the ajax call



function GetFilteredRecords() {

var filterOptions = toSimpleJson();

$.ajax({
url: '/api/workassign',
data: JSON.stringify(filterOptions),
cache: false,
type: 'GET',
dataType: 'JSON',
success: function (data) {
debugger
}
});


}

here is the filteroptions data

enter image description here


here is the api controller get action


public IEnumerable<WorkAssignViewModel> Get([FromUri]FilterViewModel date)
{

}


here i am getting the form data into json object and the passing to controller by using json.stringify() which is suggested and in controller using [FROMUri] but still values are null......

please suggest me a solution to overcome

thank you..

Answer

You need to remove the JSON.stringify() andcontentTypefrom the ajax call. You making a GET and a GET does not have a body (thereforecontentType` option is pointless). You code ajax call should be

$.ajax({
    url: '/api/workassign',
    data: filterOptions,
    cache: false,
    type: 'GET',
    dataType: 'JSON',
    success: function (data) {
        debugger
    }
});

Note that is you have generated you form controls correctly based on the view having @model FilterViewModel and using the HtmlHelper methods to generate the form controls (@Html.TextBoxFor(m => m.RegionID) etc), then you can simply use data: #('form').serialize(),

Comments