متدهای Get&Post در MVC Web Api
سه شنبه 30 دی 1393در این مقاله به نحوه استفاده از متد های get و post با ajax در api کنترلر در mvc می پردازیم
web api را معمولا خدمات آرام می نامند چون ما میتوانیم این خدمات را با استفاده از url صدا بزنیم و این نوع از خدمات برای موبایل ها و پلتفرم های مستقل مفید هستند.
به برنامه می پردازیم ابتدا باید کنترلر خود را به شکل زیر ویرایش کنیم :
public class HomeController : ApiController
{
public string GetEmployeeInformation(string JSONString)
{
var seriptSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
Employee employee = seriptSerialization.Deserialize<Employee>(JSONString);
//if list then we can use like this
//List<Employee> employee = seriptSerialization.Deserialize<List<Employee>>(JSONString);
return employee.EmployeeName;
}
public string PostSubmitdata([FromBody]Employee emp)
{
return emp.EmployeeName;
}
}
کلاس employee :
public class Employee
{
public string EmployeeName { get; set; }
public EmployeeDetails empdetails { get; set; }
}
public class EmployeeDetails
{
public string email { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
}
حالا نوبت به نوشتن کد های get و post می رسد:
<!DOCTYPE>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
/**********************************Request****************************************/
var reqdata = {
EmployeeName: "JD Mishra",
empdetails: {
email: 'jagdev@email.com',
firstName: 'Jagdev',
lastName: 'Mishra'
}
}
var stringReqdata = JSON.stringify(reqdata);
/*************************************GET*****************************************/
function GetEmployeeInformation() {
var url = "http://localhost:4000/api/Home/GetEmployeeInformation?JSONString=" + stringReqdata;
jQuery.ajax({
dataType: "json",
url: url,
async: false,
context: document.body
}).success(function (data) {
alert(data);
});
};
/*************************************GET*****************************************/
function PostSubmitdata() {
var url = "http://localhost:4000/api/Home/PostSubmitdata";
jQuery.ajax({
async: false,
type: "POST",
url: url,
data: stringReqdata,
dataType: "json",
context: document.body,
contentType: 'application/json; charset=utf-8'
}).success(function (data) {
alert(data);
})
}
</script>
</head>
<body>
<a href="#" onclick="GetEmployeeInformation();">Get</a><br />
<a href="#" onclick="PostSubmitdata();">Post</a>
</body>
</html>
حالا میتونید برنامه رو اجرا کنید.
- ASP.net MVC
- 3k بازدید
- 3 تشکر