Ajax form in asp.net MVC core 3.1
In this article we will how to insert record in database using Ajax Form in asp.net core.
- Create new asp.net core mvc project
- Enable migrations
- Create dbContext class
- Create Stored Procedure
- Create Interface (IEmployeeDbService)
- Create Class (EmployeeDbService)
- Create Controller (EmployeeDbController)
- Create Action Method(Create) in the controller
- Add View to the action method
1. Stored Procedure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | Create proc [dbo].[sp_Employee_SaveNew] @Name varchar(150), @DOB datetime, @JobTitle varchar(50), @Address varchar(200), @EmployeeID int=null output as INSERT INTO [dbo].[Employee] ([Name] ,[DOB] ,[JobTitle] ,[Address]) VALUES (@Name ,@DOB ,@JobTitle ,@Address) set @EmployeeID=SCOPE_IDENTITY(); |
EmployeeModel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace MyCoreProject.Models { public class EmployeeModel { public int EmpID { get; set; } [Required] [Display(Name="Employee Name")] public string Name { get; set; } [Required] [Display(Name="Date Of Birth")] public DateTime? DOB { get; set; } [Required] [Display(Name="Job Title")] public string JobTitle { get; set; } [Required] [Display(Name = "Address")] public string Address { get; set; } } } |
2. IEmployeeDbService
1 2 3 4 5 6 7 8 9 10 11 12 13 | using MyCoreProject.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyCoreProject.Areas.coreapi.Services { public interface IEmployeeDbService { int Create(EmployeeModel model); } } |
3. EmployeeDbService
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | using MyCoreProject.Models; using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Data.SqlClient; namespace MyCoreProject.Areas.coreapi.Services { public class EmployeeDbService : IEmployeeDbService { public int Create(EmployeeModel model) { MyDbContext _db = new MyDbContext(); DbConnection _con = _db.Database.GetDbConnection(); DbCommand _com = _con.CreateCommand(); try { var _parameters = new[] { new SqlParameter(){ ParameterName="@Name",Value=model.Name,Direction= System.Data.ParameterDirection.Input }, new SqlParameter(){ ParameterName="@DOB",Value=model.DOB,Direction= System.Data.ParameterDirection.Input }, new SqlParameter(){ ParameterName="@JobTitle",Value=model.JobTitle,Direction= System.Data.ParameterDirection.Input }, new SqlParameter(){ ParameterName="@Address",Value=model.Address,Direction= System.Data.ParameterDirection.Input }, new SqlParameter(){ ParameterName="@EmployeeID",Value=0,Size=4,Direction= System.Data.ParameterDirection.Output }, }; var _effectedRows = _db.Database.ExecuteSqlRaw("exec sp_Employee_SaveNew @Name,@DOB,@JobTitle,@Address,@EmployeeID output", _parameters); int employeeid = int.Parse(_parameters[4].Value.ToString()); return employeeid; } catch (Exception ae) { throw new Exception(ae.Message); } finally { _con.Close(); } } } } |
ConfigureServices
1 2 3 4 5 6 7 8 9 10 11 | public void ConfigureServices(IServiceCollection services) { services.AddTransient<IEmployeeDbService, EmployeeDbService>(); //services.AddTransient<IImageWriter,ImageWriter>(); services.AddMvc(); services.AddControllers().AddJsonOptions( x => x.JsonSerializerOptions.WriteIndented=true ); services.AddControllersWithViews(); services.AddDbContext<MyDbContext>(); } |
5. EmployeeDbController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using MyCoreProject.Areas.coreapi.Services; using MyCoreProject.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyCoreProject.Controllers { public class EmployeeDbController : Controller { IEmployeeDbService _employeeDbService; public EmployeeDbController(IEmployeeDbService employeeDbService) { _employeeDbService = employeeDbService; } public IActionResult Create() { EmployeeModel model = new EmployeeModel(); return View(model); } [HttpPost] public JsonResult Create(EmployeeModel model) { int empid = _employeeDbService.Create(model); return Json(new { Error = empid <= 0 ? true : false, employeeId = empid }); } } } |
6. View
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | @model MyCoreProject.Models.EmployeeModel @{ ViewData["Title"] = "Create"; } @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers <div class="row"> <div class="col-md-4"> <form asp-action="Create" asp-area="" asp-controller="EmployeeDb" data-ajax-success="CreateOnSuccess" data-ajax="true" data-ajax-method="POST"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="DOB" class="control-label"></label> <input asp-for="DOB" class="form-control" /> <span asp-validation-for="DOB" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="JobTitle" class="control-label"></label> <input asp-for="JobTitle" class="form-control" /> <span asp-validation-for="JobTitle" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Address" class="control-label"></label> <input asp-for="Address" class="form-control" /> <span asp-validation-for="Address" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} <script src="@Url.Content("~/lib/jquery-validation-unobtrusive/jquery.unobtrusive-ajax.js")"></script> <script> var CreateOnSuccess = function datasuccess(context) { console.log(context); if (context.error == false) { alert("Record Inserted") } else { alert('Error occured'); } } </script> } |
MyDbContext
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace MyCoreProject.Models { public class MyDbContext:DbContext { public MyDbContext():base() { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); optionsBuilder.UseSqlServer(configuration.GetConnectionString("MyDbConnection") ); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } DbSet<tblTest> tblTests { get; set; } } } |
appsettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 | { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "ConnectionStrings": { "MyDbConnection": "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MyDB;Data Source=(local)" }, "AllowedHosts": "*" } |
Post a Comment
Post a Comment