webapi+EF(增删改查)
第一步,Model建立Ado.net实体模型。
第二部,Controller建立增删查改方法
public static HttpResponseMessage toJson(Object obj)
{
String str;
if (obj is String || obj is Char)
{
str = obj.ToString();
}
else
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
str = serializer.Serialize(obj);
}
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
public HttpResponseMessage get()
{
var jg = db.user.ToList();
return toJson(jg);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
连接数据库:vs界面左侧服务器资源管理器中连接数据库,在web.config中修改或添加
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-webapitest1-20170420100509;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-webapitest1-20170420100509.mdf" />
<add name="testDBEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=testDB;persist security info=True;user id=sa;password=123456; MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
第三部:view视图页面 Index.cshtml
@{
Layout = null;
}
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<table id="customerTable" border="0" cellpadding="3">
<tr>
<th>UserID</th>
<th>login</th>
<th>pwd</th>
<th>Actions</th>
</tr>
<tr>
<td>
<input type="text" id="txtCustomerId" size="5" />
</td>
<td>
<input type="text" id="txtCompanyName" />
</td>
<td>
<input type="text" id="txtContactName" />
</td>
<td>
<input type="button" name="btnInsert" value="Insert" />
</td>
</tr>
</table>
<script type="text/javascript">
$(function () {
$.getJSON("api/user", LoadCustomers);
});
function LoadCustomers(data) {
$("#customerTable").find("tr:gt(1)").remove();
$.each(data, function (key, val) {
var tableRow = '<tr>' + '<td>' + val.userId + '</td>' +
'<td><input type="text" value="' + val.login + '" /></td>' +
'<td><input type="text" value="' + val.pwd + '" /></td>' +
'<td><input type="button" name="btnUpdate" value="修改" />' +
'<input type="button" name="btnDelete" value="删除" /></td>' +
'</tr>';
$('#customerTable').append(tableRow);
});
$("input[name='btnInsert']").click(OnInsert);
$("input[name='btnUpdate']").click(OnUpdate);
$("input[name='btnDelete']").click(OnDelete);
}
function OnInsert() {
var userId = $("#txtCustomerId").val();
var login = $("#txtCompanyName").val();
var pwd = $("#txtContactName").val();
var data = '{"userId":"' + userId + '","login":"' + login + '","pwd":"' + pwd + '"}}';
$.ajax({
type: 'POST',
url: '/api/user',
data: data,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (result) {
$("#txtCustomerId").val('');
$("#txtCompanyName").val('');
$("#txtContactName").val('');
$("#txtCountry").val('');
$.getJSON("api/user", LoadCustomers);
alert('Customer Added !');
}
}).fail(
function (xhr, textStatus, err) {
alert('添加失败,原因如下: ' + err);
});
}
function OnUpdate() {
var userId = $(this).parent().parent().children().get(0).innerHTML;;
var login = $($(this).parent().parent().children().get(1)).find("input").val();
var pwd = $($(this).parent().parent().children().get(2)).find("input").val();;
var data = '{"userId":"' + userId + '","login":"' + login + '","pwd":"' + pwd + '"}}';
$.ajax({
type: 'PUT',
url: '/api/user/' + userId,
data: data,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (results) {
$.getJSON("api/user", LoadCustomers);
alert('Customer Updated !');
}
}).fail(function (xhr, textStatus, err) {
alert('Failed update! The reason is : ' + err);
});
}
function OnDelete() {
var userId = $(this).parent().parent().children().get(0).innerHTML;
$.ajax({
type: 'DELETE',
url: '/api/user/' + userId,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (results) {
$.getJSON("api/user", LoadCustomers);
alert('Customer Deleted!');
}
}).fail(function (xhr, textStatus, err) {
alert("Delete error ! The reason is :" + err);
});
}
</script>