第一步:创建空的webapi
第二步:view里面添加个home文件夹
在添加个about.cshtm页面
<scriptsrc="~/Scripts/jquery-1.10.2.min.js"></script>
<scripttype="text/javascript">
$(document).ready(
function(){
$("#BtnAll").click(function () {
$.getJSON(
"/Api/Contact", function (data) {
var html = "<ul>";
$(data).each(function (i, item) {
html +="<li>"+item.ID+":"+item.Name+":"+item.Sex+"</li>";
});
html +="</ul>"
$("#ContactALL").html(html);
});
});$(
"#BtnId").click(function () {
var id = $("#txtId").val();
$.getJSON(
"/api/Contact/" + id, function (data) {
var html = "<ul>"; $(data).each(function (i, item)
{html +="<li>" + item.ID + ":" + item.Name + ":" + item.Sex + "</li>";
});
html +="</ul>";
$("#ContactId").html(html);
});
});
$("#BtnSex").click(function () {
var sex = $("#ddlsex").val();
$.getJSON("/api/Contact?sex=" + sex, function (data) {
var html = "<ul>";
$(data).each(
function (i, item) {
html+="<li>"+item.ID+":"+item.Name+":"+item.Sex+"</li>"
});
html +="</ul>";
$("#ContactSex").html(html);
});
});
});
</script>
<div>
<p>
<inputtype="button"id="BtnAll"value="查询所有"/>
</p><p>
<inputtype="text"id="txtId"/>
<inputtype="button"id="BtnId"value="根据ID查询"/>
</p><p>
<selectid="ddlsex"name="ddlsex">
<optionvalue="男">男</option>
<optionvalue="女">女</option>
</select>
<inputtype="button"id="BtnSex"value="根据sex查询"/>
</p>
<divid="ContactALL"></div>
<divid="ContactId"></div>
<divid="ContactSex"></div>
</div>
-------------------------------------------------------
后台代码:先创建个homecontroller
public ActionResult About()
{
return View();
}
在创建个contractcontroller
Contact[] Contacts = newContact[]
{
new Contact{ID=1,Name="张三",Sex="男",Birthday=Convert.ToDateTime("1991-11-05"),Age=22},
new Contact{ID=2,Name="李四",Sex="女",Birthday=Convert.ToDateTime("1990-12-05"),Age=23},
newContact{ID=3,Name="王五",Sex="男",Birthday=Convert.ToDateTime("1993-09-05"),Age=24},
newContact{ID=4,Name="赵六",Sex="女",Birthday=Convert.ToDateTime("1996-11-15"),Age=25},
};
///<summary>
/// api/contact
///</summary>
///<returns></returns>
publicIEnumerable<Contact> GetAll()
{
return Contacts;
}
///<summary>
/// API/contact/id
///</summary>
///<returns></returns>
publicContact GetContactId(int id)
{
Contact contact = Contacts.FirstOrDefault<Contact>(item => item.ID == id);
if(contact==null)
{
thrownewHttpResponseException(HttpStatusCode.NotFound);
}
return contact;
}
///<summary>
/// api/contact/sex
///</summary>
///<param name="sex"></param>
///<returns></returns>
publicIEnumerable<Contact> GetContactSex(string sex)
{
return Contacts.Where(item=>item.Sex==sex);
}
-------------------------------------------------------------------------------
创建个model contract.cs
publicint ID { get; set; }
publicstring Name { get; set; }
publicstring Sex { get; set; }
publicDateTime Birthday { get; set; }
publicint Age { get; set; }