搜尋一下Ajax就可以,
這屬於JavaScript(jQuery)的部分,
跟ASP.NET MVC沒有直接關聯.
使用別人API應用來驗證帳號密碼,跟froce說的一樣,需要使用後台呼叫API
Json Post呼叫代碼如下:
public static class HttpClientHelper
{
public static async Task PostByJsonContentTypeAsync(string url, object reqeustBody, Action<string> successFunction,Action<HttpRequestException> errorFunction, int timeout = 15)
{
var json = JsonConvert.SerializeObject(reqeustBody);
using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(timeout) })
using (var request = new HttpRequestMessage(HttpMethod.Post, url))
using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
{
request.Content = stringContent;
try
{
using (var httpResponseMessage = await client.SendAsync(request))
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
var responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
successFunction(responseBody);
}
}
catch (HttpRequestException e)
{
errorFunction(e);
}
}
}
}
使用方式:
public class Program{
public static async Task Main(string[] args)
{
//SuccessExecute
await Execute("https://jsonplaceholder.typicode.com/posts", new { value = "ITWeiHan" }); //Result : {"value": "ITWeiHan","id": 101}
//ErrorExecute
await Execute("https://jsonplaceholder.typicode.com/error404", new { value = "ITWeiHan" }); //Result : Error 404
}
public static async Task Execute(string url, object reqeustBody)
{
await HttpClientHelper.PostByJsonContentTypeAsync(url, reqeustBody
, successFunction: responsebody =>
{
//Your Success Logic
Console.WriteLine("Success");
Console.WriteLine(responsebody);
}, errorFunction: httpRequestException =>
{
//Your Error Solution Logic
Console.WriteLine("Error");
Console.WriteLine(httpRequestException.Message);
}
);
}
}