http://www.binaryintellect.net/articles/589f6915-f4c0-4bf9-9f94-4d00bd445c16.aspx
这个解决方案工作得很好。
我有一个 HTML 表单,其中所有的输入控件都是动态的。很难将表单数据连接到 MVC 控制器,然后再连接到 Web Api 2 控制器。
您的服务器端 web api 方法需要像
public string Post(FormDataCollection form){
... }
FormDataCollection 位于 System.Net.Http.Formatting 命名空间中。
如果您直接从网页 (jquery) 发送数据,那么上述链接解决方案可以正常工作。
如果您将数据网页发布到 MVC 页面(c# 代码),然后进一步发布到 web api 方法,则代码如下所示:
[HttpPost]
public async Task<string> MasterDraw(FormCollection body)
{
HttpClient client = new HttpClient();
KeyValuePair<string, string>[] list = null;
string url = ConfigurationManager.AppSettings["BaseServiceUrl"] + "/api/MasterOperation/addrecord";
if (body != null && body.HasKeys())
{
list = new KeyValuePair<string, string>[body.AllKeys.Count()];
for (int ctr = 0; ctr < body.Keys.Count; ctr++ )
{
list[ctr] = new KeyValuePair<string, string>(body.Keys[ctr], body.GetValue(body.Keys[ctr]).AttemptedValue);
}
}
var content = new FormUrlEncodedContent(list);
HttpResponseMessage response = await client.PostAsync(url, content);
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as JToken and write out top facts for each country
string contentRes = response.Content.ReadAsStringAsync().Result;
return contentRes;
}
浏览器端代码:
$('#btn-save').on('click', function (event) {
var postUrl = "@Url.Action("masterdraw","masterrender")";
var result = $.ajax({
type: "POST",
data: $('#form').serialize(),
url: postUrl
});
// insert your jquery .done and .error methods
});