ASP .NET MVC Data insert View By Ajax
At first create a C# MVC project
Create Model and Set Model data
Course.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVC_CRUD_TUTORIAL.Models
{
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public string CourseCode { get; set; }
}
}
Create DB Cotext
ProjectDB.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MVC_CRUD_TUTORIAL.Models
{
public class ProjectDB:DbContext
{
public ProjectDB(): base("mvctutorial")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Course> Courses { get; set; }
}
}
Create Controller
CourseController.cs
using MVC_CRUD_TUTORIAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_CRUD_TUTORIAL.Controllers
{
public class CourseController : Controller
{
ProjectDB aContext = new ProjectDB();
// GET: Course
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Course aCourse )
{
aContext.Courses.Add(aCourse);
aContext.SaveChanges();
ViewBag.Message = "Succesfully Saved";
return View();
}
public JsonResult SaveCourse(Course aCourse)
{
aContext.Courses.Add(aCourse);
aContext.SaveChanges();
var CourseList = aContext.Courses.ToList();
return Json(CourseList, JsonRequestBehavior.AllowGet);
}
}
}
Create View File
Index.cshtml
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>
@if (ViewBag.Message != null)
{
<label>@ViewBag.Message</label>
}
<form method="POST">
@Html.AntiForgeryToken()
<label>Course Name</label>
<input type="text" name="CourseName" id="CourseName" />
<label>Course Code</label>
<input type="text" name="CourseCode" id="CourseCode" />
<input type="button" value="Save" id="Save" />
</form>
<table id="CourseData">
<thead>
<tr>
<th>Course name</th>
<th>Course Code</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="~/Scripts/jquery-3.6.0.js"></script>
<script>
$(document).ready(function () {
$("#CourseData").hide();
$("#Save").click(function () {
var CourseName = $("#CourseName").val();
var CourseCode = $("#CourseCode").val();
var jsonData = { CourseName: CourseName, CourseCode: CourseCode };
$.ajax({
type: "POST",
url: '@Url.Action("SaveCourse","Course")',
contentType: "application/json;charest=utf-8",
data:JSON.stringify(jsonData),
dataType: "json",
success: function (data) {
$("#CourseData").show();
$("#CourseData tbody").empty();
$.each(data, function (key, value) {
$("#CourseData tbody").append('<tr><td>' + value.CourseName + '</td><td>' + value.CourseCode + '</td></tr>');
});
//alert("Success");
}
});
return false;
});
})
</script>
</div>
No comments