1648887900
WEB APIは、HTTP / Restfulを使用してリソース指向のサービスを作成するのに最適であり、MVCベースのアプリケーションでうまく機能します。詳細については、私のリンクをご覧ください。
説明
このセッションでは、HttpClientを使用してAA Web APIを使用してレコードを挿入し、SQLServerにデータを投稿する方法を紹介します。このセッションでは、WebAPIによるgetおよびpost操作を確認できます。別の言い方をすれば、ボタンクリックイベントを使用してレコードを挿入および取得すると言えます。
このセッションを行う前に、前のセッションにアクセスしてください。
従うべきステップ、
ステップ1
HTTPクライアントを使用してデータを取得するためのビューを取得するための新しいアクションを(MVCクライアントアプリケーションの)HomeControllerに追加します。
コード参照
public ActionResult Part4()
{
List<Employee> list = new List<Employee>();
HttpClient client = new HttpClient();
var result = client.GetAsync("http://localhost:47250/api/satya").Result;
if (result.IsSuccessStatusCode)
{
list = result.Content.ReadAsAsync<List<Employee>>().Result;
ViewBag.userdetails = list;
}
return View();
}
コードの説明
ページの初期ロード中にテーブルデータが表示されます。これは、データがHttpClientを使用する入力コントロールを使用してテーブルにバインドされることを意味します。[HttpGet]を使用したこのコントローラーアクションメソッド。
ステップ2
HTTPクライアントを使用した投稿データのHomeController(MVCクライアントアプリケーション内)に対して同じアクションを使用します。
コード参照
[HttpPost]
public ActionResult Part4(Employee emp)
{
if (ModelState.IsValid)
{
HttpClient client = new HttpClient();
var result = client.PostAsJsonAsync("http://localhost:47250/api/satya", emp).Result;
if (result.IsSuccessStatusCode)
{
emp = result.Content.ReadAsAsync<Employee>().Result;
ViewBag.Result = "Data Is Successfully Saved!";
List<Employee> list = new List<Employee>();
HttpClient client1 = new HttpClient();
var result1 = client1.GetAsync("http://localhost:47250/api/satya").Result;
if (result1.IsSuccessStatusCode)
{
list = result1.Content.ReadAsAsync<List<Employee>>().Result;
ViewBag.userdetails = list;
}
ModelState.Clear();
return View(new Employee());
}
else
{
ViewBag.Result = "Error! Please try with valid data.";
}
}
return View(emp);
}
コードの説明
この部分では、フォームのPOSTメソッドまたはボタンクリックイベントの後、データ挿入とテーブルデータが表示されます。サイドポストセクションでは、データ取得のためのsoemthingを追加しました。そうしないと、オブジェクト参照がオブジェクトのインスタンスに設定されていないというエラーが発生します。この問題については、注のビューセクションで説明します。
HttpClient client1 = new HttpClient();
var result1 = client1.GetAsync("http://localhost:47250/api/satya").Result;
if (result1.IsSuccessStatusCode)
{
list = result1.Content.ReadAsAsync<List<Employee>>().Result;
ViewBag.userdetails = list;
}
モデルの状態とモデルバインディング検証の状態を含むモデル状態ディクショナリオブジェクトは、モデル状態ディクショナリからすべてのアイテムを削除します。
ModelState.Clear();
ステップ3
アクションメソッドを右クリックします(ここではフォームPart4()を右クリックします)>ビューの追加...>[強く型付けされたビューの作成]をオンにします>モデルクラスを選択します>>追加します。ここでのモデルクラスは「従業員(エンティティ)」です。
コード参照
@model Entities.Employee
@{
ViewBag.Title = "Satyaprakash - Post data to Web API using HTTPClient (in MVC client application) With Validation";
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">
</script>
<style>
span.field-validation-error {
color: red;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.button4 {
border-radius: 9px;
}
</style>
<div style="padding:10px ; align-content:center">
<fieldset>
<legend style="font-family:Arial Black;color:blue">Post data to Web API using HTTPClient (in MVC client application) With Validation</legend>
</fieldset>
</div>
<div style="max-width:600px;">
@using (Html.BeginForm("Part4", "Home", FormMethod.Post, new { role = "form" }))
{
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(a => a.FirstName)
@Html.TextBoxFor(a => a.FirstName, new { @class = "form-control" })
@Html.ValidationMessageFor(a => a.FirstName)
</div>
<div class="form-group">
@Html.LabelFor(a => a.LastName)
@Html.TextBoxFor(a => a.LastName, new { @class = "form-control" })
@Html.ValidationMessageFor(a => a.LastName)
</div>
<div class="form-group">
@Html.LabelFor(a => a.EmailID)
@Html.TextBoxFor(a => a.EmailID, new { @class = "form-control" })
@Html.ValidationMessageFor(a => a.EmailID)
</div>
<div class="form-group">
@Html.LabelFor(a => a.City)
@Html.TextBoxFor(a => a.City, new { @class = "form-control" })
@Html.ValidationMessageFor(a => a.City)
</div>
<div class="form-group">
@Html.LabelFor(a => a.Country)
@Html.TextBoxFor(a => a.Country, new { @class = "form-control" })
@Html.ValidationMessageFor(a => a.Country)
</div>
<input id="btn" type="submit" value="Create" class="button button4" />
<div style="width:90%; padding:10px; margin:0 auto;">
@if (ViewBag.Result != null)
{
@*<div style="color:red">@ViewBag.Result</div>*@
<script>
$(document).ready(function () {
$('#btn').click(function () {
$('#tableshow').hide();
});
bootbox.alert('@ViewBag.Result');
$('#tableshow').show();
});
</script>
}
</div>
}
</div>
@*System.NullReferenceException , Object reference not set to an instance of an object. This error due to without added for data retrieve comment line code in Part4() in homecontroller in webapplication*@
<div id="tableshow" style="width:90%; padding:10px; margin:0 auto;">
<table class="table table-responsive table-striped table-bordered">
<thead>
<tr>
<th style="background-color: Yellow;color: blue">Full Name</th>
<th style="background-color: Yellow;color: blue">Email</th>
<th style="background-color: Yellow;color: blue">City</th>
<th style="background-color: Yellow;color: blue">Country</th>
</tr>
</thead>
<tbody>
@foreach (var i in ViewBag.userdetails)
{
<tr>
<td>@i.FirstName @i.LastName</td>
<td>@i.EmailID</td>
<td>@i.City</td>
<td>@i.Country</td>
</tr>
}
</tbody>
</table>
</div>
@*System.NullReferenceException , Object reference not set to an instance of an object.*@
@section Scripts{
@Scripts.Render("~/bundles/jqueryval")
}
コードの説明
フォームポストメソッド内のこのコードセクションにスクリプトを追加して、ボタンクリック中にイベントテーブルデータが表示されるようにしました。
<div style="width:90%; padding:10px; margin:0 auto;">
@if (ViewBag.Result != null)
{
@*<div style="color:red">@ViewBag.Result</div>*@
<script>
$(document).ready(function () {
$('#btn').click(function () {
$('#tableshow').hide();
});
bootbox.alert('@ViewBag.Result');
$('#tableshow').show();
});
</script>
}
</div>
ここでは、ブートボックスライブラリを使用してアラート通知を表示しました。ViewBag.Resultには、コントローラーアクションメソッドのメッセージが含まれています。
bootbox.alert('@ViewBag.Result');
ノート
このセッション中に、System.NullReferenceExceptionに関する問題が発生しました。オブジェクト参照が、オブジェクトのインスタンスに設定されていません。
そこで、Part4()コントローラーアクションメソッドのpostメソッドで説明されているように、iIはdiv idを作成し、スクリプトセクション内に配置しました。このエラーは、MVCクライアントアプリケーションのホームコントローラーのPart4()にデータ取得コメント行コードのデータが追加されていないことが原因でした。
<div id="tableshow" style="width:90%; padding:10px; margin:0 auto;">
<table class="table table-responsive table-striped table-bordered">
<thead>
<tr>
<th style="background-color: Yellow;color: blue">Full Name</th>
<th style="background-color: Yellow;color: blue">Email</th>
<th style="background-color: Yellow;color: blue">City</th>
<th style="background-color: Yellow;color: blue">Country</th>
</tr>
</thead>
<tbody>
@foreach (var i in ViewBag.userdetails)
{
<tr>
<td>@i.FirstName @i.LastName</td>
<td>@i.EmailID</td>
<td>@i.City</td>
<td>@i.Country</td>
</tr>
}
</tbody>
</table>
</div>
出力
ページ読み込みイベント中。
モバイルビューのサポート。
出力についてよりよく理解するためのGIF画像。
上の画像に示すように、SQLサーバーでレコードの挿入を確認してください。
ソースコードへのリンク
まとめ
前の部分-
パート1- MVCとエンティティフレームワークを使用したASP.NETWebAPI
パート2-データを取得するためにMVC、エンティティフレームワーク、jQueryを使用するASP.NET Web API
パート3- ASP.NETWebAPIでクラスライブラリを使用して、エンティティデータモデル(.edmx)のモデルクラスを複数のプロジェクトに再利用する
パート4-
データを取得するためにMVC、Entity Framework、およびHttpClientを使用するASP.NET Web API
パート5-検証付きの取得と投稿にMVC、Entity Framework、jQueryを使用したASP.NET Web API
#aspdotnet #mvc #entity-framework
1648887900
WEB APIは、HTTP / Restfulを使用してリソース指向のサービスを作成するのに最適であり、MVCベースのアプリケーションでうまく機能します。詳細については、私のリンクをご覧ください。
説明
このセッションでは、HttpClientを使用してAA Web APIを使用してレコードを挿入し、SQLServerにデータを投稿する方法を紹介します。このセッションでは、WebAPIによるgetおよびpost操作を確認できます。別の言い方をすれば、ボタンクリックイベントを使用してレコードを挿入および取得すると言えます。
このセッションを行う前に、前のセッションにアクセスしてください。
従うべきステップ、
ステップ1
HTTPクライアントを使用してデータを取得するためのビューを取得するための新しいアクションを(MVCクライアントアプリケーションの)HomeControllerに追加します。
コード参照
public ActionResult Part4()
{
List<Employee> list = new List<Employee>();
HttpClient client = new HttpClient();
var result = client.GetAsync("http://localhost:47250/api/satya").Result;
if (result.IsSuccessStatusCode)
{
list = result.Content.ReadAsAsync<List<Employee>>().Result;
ViewBag.userdetails = list;
}
return View();
}
コードの説明
ページの初期ロード中にテーブルデータが表示されます。これは、データがHttpClientを使用する入力コントロールを使用してテーブルにバインドされることを意味します。[HttpGet]を使用したこのコントローラーアクションメソッド。
ステップ2
HTTPクライアントを使用した投稿データのHomeController(MVCクライアントアプリケーション内)に対して同じアクションを使用します。
コード参照
[HttpPost]
public ActionResult Part4(Employee emp)
{
if (ModelState.IsValid)
{
HttpClient client = new HttpClient();
var result = client.PostAsJsonAsync("http://localhost:47250/api/satya", emp).Result;
if (result.IsSuccessStatusCode)
{
emp = result.Content.ReadAsAsync<Employee>().Result;
ViewBag.Result = "Data Is Successfully Saved!";
List<Employee> list = new List<Employee>();
HttpClient client1 = new HttpClient();
var result1 = client1.GetAsync("http://localhost:47250/api/satya").Result;
if (result1.IsSuccessStatusCode)
{
list = result1.Content.ReadAsAsync<List<Employee>>().Result;
ViewBag.userdetails = list;
}
ModelState.Clear();
return View(new Employee());
}
else
{
ViewBag.Result = "Error! Please try with valid data.";
}
}
return View(emp);
}
コードの説明
この部分では、フォームのPOSTメソッドまたはボタンクリックイベントの後、データ挿入とテーブルデータが表示されます。サイドポストセクションでは、データ取得のためのsoemthingを追加しました。そうしないと、オブジェクト参照がオブジェクトのインスタンスに設定されていないというエラーが発生します。この問題については、注のビューセクションで説明します。
HttpClient client1 = new HttpClient();
var result1 = client1.GetAsync("http://localhost:47250/api/satya").Result;
if (result1.IsSuccessStatusCode)
{
list = result1.Content.ReadAsAsync<List<Employee>>().Result;
ViewBag.userdetails = list;
}
モデルの状態とモデルバインディング検証の状態を含むモデル状態ディクショナリオブジェクトは、モデル状態ディクショナリからすべてのアイテムを削除します。
ModelState.Clear();
ステップ3
アクションメソッドを右クリックします(ここではフォームPart4()を右クリックします)>ビューの追加...>[強く型付けされたビューの作成]をオンにします>モデルクラスを選択します>>追加します。ここでのモデルクラスは「従業員(エンティティ)」です。
コード参照
@model Entities.Employee
@{
ViewBag.Title = "Satyaprakash - Post data to Web API using HTTPClient (in MVC client application) With Validation";
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">
</script>
<style>
span.field-validation-error {
color: red;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.button4 {
border-radius: 9px;
}
</style>
<div style="padding:10px ; align-content:center">
<fieldset>
<legend style="font-family:Arial Black;color:blue">Post data to Web API using HTTPClient (in MVC client application) With Validation</legend>
</fieldset>
</div>
<div style="max-width:600px;">
@using (Html.BeginForm("Part4", "Home", FormMethod.Post, new { role = "form" }))
{
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(a => a.FirstName)
@Html.TextBoxFor(a => a.FirstName, new { @class = "form-control" })
@Html.ValidationMessageFor(a => a.FirstName)
</div>
<div class="form-group">
@Html.LabelFor(a => a.LastName)
@Html.TextBoxFor(a => a.LastName, new { @class = "form-control" })
@Html.ValidationMessageFor(a => a.LastName)
</div>
<div class="form-group">
@Html.LabelFor(a => a.EmailID)
@Html.TextBoxFor(a => a.EmailID, new { @class = "form-control" })
@Html.ValidationMessageFor(a => a.EmailID)
</div>
<div class="form-group">
@Html.LabelFor(a => a.City)
@Html.TextBoxFor(a => a.City, new { @class = "form-control" })
@Html.ValidationMessageFor(a => a.City)
</div>
<div class="form-group">
@Html.LabelFor(a => a.Country)
@Html.TextBoxFor(a => a.Country, new { @class = "form-control" })
@Html.ValidationMessageFor(a => a.Country)
</div>
<input id="btn" type="submit" value="Create" class="button button4" />
<div style="width:90%; padding:10px; margin:0 auto;">
@if (ViewBag.Result != null)
{
@*<div style="color:red">@ViewBag.Result</div>*@
<script>
$(document).ready(function () {
$('#btn').click(function () {
$('#tableshow').hide();
});
bootbox.alert('@ViewBag.Result');
$('#tableshow').show();
});
</script>
}
</div>
}
</div>
@*System.NullReferenceException , Object reference not set to an instance of an object. This error due to without added for data retrieve comment line code in Part4() in homecontroller in webapplication*@
<div id="tableshow" style="width:90%; padding:10px; margin:0 auto;">
<table class="table table-responsive table-striped table-bordered">
<thead>
<tr>
<th style="background-color: Yellow;color: blue">Full Name</th>
<th style="background-color: Yellow;color: blue">Email</th>
<th style="background-color: Yellow;color: blue">City</th>
<th style="background-color: Yellow;color: blue">Country</th>
</tr>
</thead>
<tbody>
@foreach (var i in ViewBag.userdetails)
{
<tr>
<td>@i.FirstName @i.LastName</td>
<td>@i.EmailID</td>
<td>@i.City</td>
<td>@i.Country</td>
</tr>
}
</tbody>
</table>
</div>
@*System.NullReferenceException , Object reference not set to an instance of an object.*@
@section Scripts{
@Scripts.Render("~/bundles/jqueryval")
}
コードの説明
フォームポストメソッド内のこのコードセクションにスクリプトを追加して、ボタンクリック中にイベントテーブルデータが表示されるようにしました。
<div style="width:90%; padding:10px; margin:0 auto;">
@if (ViewBag.Result != null)
{
@*<div style="color:red">@ViewBag.Result</div>*@
<script>
$(document).ready(function () {
$('#btn').click(function () {
$('#tableshow').hide();
});
bootbox.alert('@ViewBag.Result');
$('#tableshow').show();
});
</script>
}
</div>
ここでは、ブートボックスライブラリを使用してアラート通知を表示しました。ViewBag.Resultには、コントローラーアクションメソッドのメッセージが含まれています。
bootbox.alert('@ViewBag.Result');
ノート
このセッション中に、System.NullReferenceExceptionに関する問題が発生しました。オブジェクト参照が、オブジェクトのインスタンスに設定されていません。
そこで、Part4()コントローラーアクションメソッドのpostメソッドで説明されているように、iIはdiv idを作成し、スクリプトセクション内に配置しました。このエラーは、MVCクライアントアプリケーションのホームコントローラーのPart4()にデータ取得コメント行コードのデータが追加されていないことが原因でした。
<div id="tableshow" style="width:90%; padding:10px; margin:0 auto;">
<table class="table table-responsive table-striped table-bordered">
<thead>
<tr>
<th style="background-color: Yellow;color: blue">Full Name</th>
<th style="background-color: Yellow;color: blue">Email</th>
<th style="background-color: Yellow;color: blue">City</th>
<th style="background-color: Yellow;color: blue">Country</th>
</tr>
</thead>
<tbody>
@foreach (var i in ViewBag.userdetails)
{
<tr>
<td>@i.FirstName @i.LastName</td>
<td>@i.EmailID</td>
<td>@i.City</td>
<td>@i.Country</td>
</tr>
}
</tbody>
</table>
</div>
出力
ページ読み込みイベント中。
モバイルビューのサポート。
出力についてよりよく理解するためのGIF画像。
上の画像に示すように、SQLサーバーでレコードの挿入を確認してください。
ソースコードへのリンク
まとめ
前の部分-
パート1- MVCとエンティティフレームワークを使用したASP.NETWebAPI
パート2-データを取得するためにMVC、エンティティフレームワーク、jQueryを使用するASP.NET Web API
パート3- ASP.NETWebAPIでクラスライブラリを使用して、エンティティデータモデル(.edmx)のモデルクラスを複数のプロジェクトに再利用する
パート4-
データを取得するためにMVC、Entity Framework、およびHttpClientを使用するASP.NET Web API
パート5-検証付きの取得と投稿にMVC、Entity Framework、jQueryを使用したASP.NET Web API