如何使用ajax将数据从View传递给对象Controller?

时间:2013-05-02 12:18:21

标签: asp.net-mvc json jquery asp.net-mvc-4

我有一个像这样的搜索ajax请求:

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

      }
    });

在GetPeole操作中,我可以获取我的参数(FirstName,LastName)

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

如果我改变我的ajax请求,如

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

      }
    });

我必须改变我的GetPeople

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

我希望将我的搜索参数(FirstName,LastName,Age)作为此类Getpeople中的对象

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

1 个答案:

答案 0 :(得分:1)

您为参数声明了一个类,如下所示:

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

并在控制器中使用它,如下所示:

public JsonResult GetPeople(SearchFilters filters) {
}

在你的ajax帖子中你需要传递这样的数据:

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