1648865460
WEB APIは、HTTP / Restfulを使用してリソース指向のサービスを作成するのに最適であり、MVCベースのアプリケーションでうまく機能します。詳細については、私のリンクをご覧ください。
説明
このセッションでは、Asp.net Web APIを使用してレコードを挿入する方法、またはSQLServerにデータを投稿する方法を紹介します。このセッションでは、WebAPIによるgetおよびpost操作を確認できます。別の言い方をすれば、ボタンクリックイベントを使用してレコードを挿入および取得すると言えます。
このセッションを行う前に、前のセッションにアクセスしてください。
ソースコード
従うべきステップ。
ステップ1
モデルに検証を適用します。
ソリューションエクスプローラー>エンティティ(プロジェクト名)>Satyadatabasemodel.tt>OpenEmployee.csに移動します。
コード参照
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Entities
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Employee
{
public int EmployeeID { get; set; }
[Required(ErrorMessage = "First name required", AllowEmptyStrings = false)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last name required", AllowEmptyStrings = false)]
public string LastName { get; set; }
[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
ErrorMessage = "E-mail is not valid")]
public string EmailID { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
}
コードの説明
ここでは、名、姓、および電子メールフィールドに検証を適用しました。名と名前が空の場合、検証メッセージが表示されます。電子メールフィールドの場合、ユーザーが誤ったドメインアドレスで無効なメールアドレスを入力すると、電子メール検証メッセージがエンドユーザーに表示されます。
ステップ2
投稿データ用のSatyaWebApiWebAPIプロジェクトのSatyaControllerに新しいアクションを追加します。
コード参照
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Entities;
namespace SatyaWebApi.Controllers
{
public class SatyaController : ApiController
{
public HttpResponseMessage Get()
{
List<Employee> allEmp = new List<Employee>();
using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
{
allEmp = dc.Employees.OrderBy(a => a.FirstName).ToList();
HttpResponseMessage response;
response = Request.CreateResponse(HttpStatusCode.OK, allEmp);
return response;
}
}
public HttpResponseMessage Post(Employee emp)
{
HttpResponseMessage response;
if (ModelState.IsValid)
{
using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
{
dc.Employees.Add(emp);
dc.SaveChanges();
}
response = Request.CreateResponse(HttpStatusCode.Created, emp);
//added for get
List<Employee> allEmp = new List<Employee>();
using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
{
allEmp = dc.Employees.OrderBy(a => a.FirstName).ToList();
HttpResponseMessage response1;
response1 = Request.CreateResponse(HttpStatusCode.OK, allEmp);
return response1;
}
}
else
{
response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error! Please try again with valid data.");
}
return response;
}
}
}
コードの説明
このコードでは、投稿データを実行するための投稿コントローラーアクションメソッドと、投稿アクションメソッド内のデータの取得に関するコードを追加しました。以下のコードはデータを取得するためのものです。
//added for get
List<Employee> allEmp = new List<Employee>();
using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
{
allEmp = dc.Employees.OrderBy(a => a.FirstName).ToList();
HttpResponseMessage response1;
response1 = Request.CreateResponse(HttpStatusCode.OK, allEmp);
return response1;
}
データを挿入するコード、
HttpResponseMessage response;
if (ModelState.IsValid)
{
using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
{
dc.Employees.Add(emp);
dc.SaveChanges();
}
response = Request.CreateResponse(HttpStatusCode.Created, emp);
dc.Employees.Add(emp);
dc.SaveChanges();
ここで、datacontextオブジェクトを使用すると、データが追加され、アクション後のメソッドのempパラメーターに渡され、これで行われたすべての変更が基になるデータベースに保存されます。
else
{
response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error! Please try again with valid data.");
}
ポストオペレーション中に接続の問題が見つかった場合、またはコードに関連する問題や無効なデータが見つかった場合は、エラーメッセージがエンドユーザーに表示されます。
ステップ3
SatyaConsumingApiのHomeControllerに新しいアクションを追加して、Postデータのビューを取得します。
コード参照
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using Entities;
namespace SatyaConsumingApi.Controllers
{
public class HomeController : Controller
{
public ActionResult Part1()
{
return View();
}
public ActionResult Part2()
{
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;
}
return View(list);
}
public ActionResult Part3()
{
return View();
}
}
}
コードの説明
ここでパート3は、MVCクライアントアプリケーションの新しいコントローラーアクションメンションです。
ステップ4
アクションのビューを追加します。
コード参照
@{
ViewBag.Title = "Satyaprakash - Post Data To Web API Using jQuery 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>
.error, #error {
color: red;
display: none;
}
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 jQuery With Validation</legend>
</fieldset>
</div>
<div class="container1">
<form id="frm1" role="form" style="max-width:500px">
<div class="form-group">
<div id="error"> </div>
</div>
<div class="form-group">
<label for="firstname" style="color:blue">First Name:</label>
<input type="text" class="form-control" id="firstname" placeholder="please enter First Name">
<span class="error">Please provide First Name</span>
</div>
<div class="form-group">
<label for="lastname" style="color:blue">Last Name:</label>
<input type="text" class="form-control" id="lastname" placeholder="please enter Last Name">
<span class="error">Please provide Last Name</span>
</div>
<div class="form-group">
<label for="email" style="color:blue">Email:</label>
<input type="text" class="form-control" id="email" placeholder="please enter Email-Id">
<span class="error">Invalid email ID</span>
</div>
<div class="form-group">
<label for="city" style="color:blue">City:</label>
<input type="text" class="form-control" id="city" placeholder="please enter City">
</div>
<div class="form-group">
<label for="country" style="color:blue">Country:</label>
<input type="text" class="form-control" id="country" placeholder="please enter Country">
</div>
<button type="submit" class="button button4">Submit</button>
</form>
</div>
<div id="updatePanel" style="width:90%; margin:0 auto; padding:10px">
</div>
@section Scripts{
<script>
$(document).ready(function () {
var apiBaseUrl = "http://localhost:47250/";
$('#frm1').submit(function (e) {
e.preventDefault();
var isOK = ValidateForm();
if (isOK) {
var emp = {
EmployeeID: 0,
FirstName: $('#firstname').val().trim(),
LastName: $('#lastname').val().trim(),
EmailID: $('#email').val().trim(),
City: $('#city').val().trim(),
Country: $('#country').val().trim()
};
//Save
$.ajax({
url: apiBaseUrl+'api/satya',
type: 'POST',
dataType: 'json',
data: emp,
success: function (d) {
bootbox.alert('Data Is Successfully Saved!');
var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');
var $header = $('<thead/>').html('<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>');
$table.append($header);
$.each(d, function (i, val) {
var $row = $('<tr/>');
$row.append($('<td/>').html(val.FirstName + ' ' + val.LastName));
$row.append($('<td/>').html(val.EmailID));
$row.append($('<td/>').html(val.City));
$row.append($('<td/>').html(val.Country));
$table.append($row);
});
$('#updatePanel').html($table);
var frm = document.getElementById('frm1');
frm.reset();
},
error: function () {
$('#error').html('Error! please try with valid data.').show();
}
});
}
});
});
function ValidateForm() {
var isAllValid = true;
$('.error').hide();
$('#error').empty();
$('.form-group').removeClass('has-error');
if ($('#firstname').val().trim()=="") {
$('#firstname').focus();
$('#firstname').siblings('.error').show();
$('#firstname').parents('.form-group').addClass('has-error');
isAllValid = false;
}
if ($('#lastname').val().trim() == "") {
$('#lastname').focus();
$('#lastname').siblings('.error').show();
$('#lastname').parents('.form-group').addClass('has-error');
isAllValid = false;
}
if ($('#email').val().trim() != "") {
var expr = /^([a-zA-Z0-9_\-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!expr.test($('#email').val().trim())) {
$('#email').focus();
$('#email').siblings('.error').show();
$('#email').parents('.form-group').addClass('has-error');
isAllValid = false;
}
}
return isAllValid;
}
</script>
}
コードの説明
「ValidateForm()」という名前のフォームコントロールを検証するためのスクリプト関数を作成しました。検証に成功すると、ポストデータ操作が実行され、ポスト操作が成功した後にデータが取得されます。その後、すべての入力フィールドがリセットされます。そうでない場合、無効なデータが原因でエラーメッセージが表示されます。
$.ajax({
url: apiBaseUrl+'api/satya',
type: 'POST',
dataType: 'json',
data: emp,
success: function (d) {
bootbox.alert('Data Is Successfully Saved!');
var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');
var $header = $('<thead/>').html('<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>');
$table.append($header);
$.each(d, function (i, val) {
var $row = $('<tr/>');
$row.append($('<td/>').html(val.FirstName + ' ' + val.LastName));
$row.append($('<td/>').html(val.EmailID));
$row.append($('<td/>').html(val.City));
$row.append($('<td/>').html(val.Country));
$table.append($row);
});
$('#updatePanel').html($table);
var frm = document.getElementById('frm1');
frm.reset();
},
error: function () {
$('#error').html('Error! please try with valid data.').show();
}
});
ブートボックスアラートメッセージをサポートするには、CDNリファレンスを追加する必要があります。
bootbox.alert('Data Is Successfully Saved!');
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">
</script>
ステップ5
_Layout.cshtmlに見栄えを良くするためにブートストラップcssを追加します。
@* @Styles.Render("~/Content/css")*@
@* Add bootstrap css for good looks *@
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
@Scripts.Render("~/bundles/modernizr")
出力
パート3のビューは次のようになります。
名と姓の検証用...
電子メールフィールドの検証用。
アラートメッセージを成功させるには、ブートボックスjavascriptライブラリを使用してデータを投稿します。
投稿データが成功したら、データを取得するか、データをテーブルにバインドします。
データベースでレコード挿入操作を確認してください。
タブレットや携帯電話向けのレスポンシブウェブページ。
理解を深めるためのGIF画像。
まとめ
#aspdotnet #mvc #entityframework
1624330946
#aspdotnetexplorer
#repository
#pattern
https://www.youtube.com/watch?v=q6Y1asskM3g
#asp.net mvc #entity framework #repository pattern #asp.net mvc using entity framework
1624381768
#aspdotnetexplorer
#mvc
#repository
#pattern
https://youtu.be/VirunHolYjA
#asp.net mvc #entity framework #repository pattern #asp.net mvc using entity framework with repository pattern
1607084960
The Model-View-Controller (MVC) is an architectural style dividing an application into three main system elements: the model, the view, and the controller. Every one of these elements is designed to manage particular aspects of an application’s growth. To build scalable and extensible projects, MVC is one of the most commonly used industry-standard web design platforms.
MVC Elements
Following are the elements of MVC:
Model
All the data-related logic that the user works with corresponds to the Model part. It can represent either the data that is being transmitted between the elements of the View and Controller or some other data relevant to business logic. A customer object, for example, retrieves customer information from the database, manipulates it and updates its data back to the database, or utilizes this for information rendering.
View
For all of the application’s UI logic, the View element has been used. For example, all the UI elements such as text boxes, dropdowns, etc. That the final user communicates with will be included in the Customer’s perspective.
Controller
In order to manage all business rules and incoming requests, controllers serve as an interface between the Model And View elements, modify data using the Model component, and communicate with the Views to make the final performance. For example, the Customer Controller will handle all the Customer View interactions and inputs, and the database will be modified using the Customer Model. To display customer information, the same controller will be used.
ASP.NET MVC:
ASP.NET supports three main growth models: Web sites, Web Forms and MVC (Model View Controller).
ASP.NET MVC Features
ASP.NET MVC provides the following characteristics :
#mvc course in chennai #mvc #mvc training in chennai #mvc training #mvc course
1623858119
#aspdotnetexplorer
#mvc
#repository
https://www.youtube.com/watch?v=tpJrrxpC_j8
#entity framework #ef repository #asp.net mvc #entity framework code first approach #c#
1602668764
Today, the Entity Framework Core team announces the second release candidate (RC2) of EF Core 5.0. This is a feature complete release candidate of EF Core 5.0 and ships with a “go live” license. You are supported using it in production. This is a great opportunity to start using EF Core 5.0 early while there is still time to fix remaining issues. We’re looking for reports of any remaining critical bugs that should be fixed before the final release.
EF Core 5.0 will not run on .NET Standard 2.0 platforms, including .NET Framework.
EF Core is distributed exclusively as a set of NuGet packages. For example, to add the SQL Server provider to your project, you can use the following command using the dotnet tool:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 5.0.0-rc.2.20475.6
#.net #.net core #.net framework #asp.net #c# #entity framework #announcement #asp.net core #entity framework core