M.Azad
M.Azad

Reputation: 3763

how to pass data from View to as an object Controller using ajax?

I have a search ajax request like this:

  $.ajax({
        type: 'POST',
        data: { FirstName: firstname, LastName: lastname},
        contentType: "application/json; charset=utf-8",
        url: 'GetPeople',
        dataType: 'json',

      }
    });

In GetPeole action I can get my parameter (FirstName,LastName)

public virtual JsonResult GetPeople(string FirstName,string LastName)
        {
          ....
        }

If i change my ajax request like

$.ajax({
        type: 'POST',
        data: { FirstName: firstname, LastName: lastname,Age=age},
        contentType: "application/json; charset=utf-8",
        url: 'GetPeople',
        dataType: 'json',

      }
    });

I must change my GetPeople

 public virtual JsonResult GetPeople(string FirstName,string LastName,int Age)
        {
          ....
        }

I want get my searchparameters(FirstName,LastName,Age) as an object in Getpeople like this

public virtual JsonResult GetPeople(searchParam)
    {
        .....
    }

Upvotes: 0

Views: 1129

Answers (1)

von v.
von v.

Reputation: 17118

You declare a class for your parameter like so:

public class SearchFilters {
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int Age {get;set;}
}

and use it in your controller like this:

public JsonResult GetPeople(SearchFilters filters) {
}

and in your ajax post you need to pass the data like this:

data: JSON.stringify({ FirstName: firstname, LastName: lastname,Age=age})

Upvotes: 2

Related Questions