[英]How to pass objects using WebRequest (without model) to External Web Api ASP.NET MVC
我有一個 asp.net MVC 和外部 WEBAPI。 我想按以下順序傳遞數據:
問題:它可以保存到數據庫,但所有值都是 0。似乎我傳遞的對象在某處丟失了,但我不知道在哪里。
真的需要這方面的幫助。 謝謝
下面是我調用 MVC 控制器的 Ajax 代碼:
function savePostApplication(theData) {
var insert = {};
insert.JobTitleId = JobTitleId;
insert.Division = Division;
insert.SalaryScaleId = SalaryScaleId;
insert.DepartmentId = DepartmentId;
insert.MinistryId = MinistryId;
$.post("/Advert/AddAdvertApplication", theData,
function (response) {
alert(response);
});
}
這是我的 MVC 控制器代碼:
public String AddAdvertApplication(JSON data)
{
var url = "https://localhost:44331/api/jobadvertisementdetails";
var wr = WebRequest.Create(url);
wr.Method = "POST";
string json = JsonConvert.SerializeObject(data);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
wr.ContentType = "application/x-www-form-urlencoded";
wr.ContentLength = byteArray.Length;
var dataStream = wr.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = wr.GetResponse();
var Status = ((HttpWebResponse)response).StatusDescription;
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
這是我的 WEBAPI 代碼:
public String PostJobAdvertisementDetail(JobAdvertisementDetail jobAdvertisementDetail)
{
try
{
DataTable table = new DataTable();
String query = @"insert into dbo.JobAdvertisementDetails (JobTitleId, Division, SalaryScaleId, DepartmentId, MinistryId) values (" + jobAdvertisementDetail.JobTitleId +
@"," + jobAdvertisementDetail.Division + "," + jobAdvertisementDetail.SalaryScaleId +
@","+jobAdvertisementDetail.DepartmentId+","+jobAdvertisementDetail.MinistryId+")";
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["CONN"].ConnectionString))
using(var cmd = new SqlCommand(query, con))
using(var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.Text;
da.Fill(table);
}
return "Data Saved";
}
catch (Exception ex)
{
return "Error";
}
}
更新:現在可以使用了。 我只是將內容類型從“application/x-www-form-urlencoded”更改為“application/json”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.