Web APP con ASP .NET CORE MVC

Posted by on Jun 23, 2019 in Tutorials | 0 comments

Web APP con ASP .NET CORE MVC

Vamos a crear una Web App con las siguientes tecnologías:
Visual Studio 2017
ASP .NET CORE MVC
Microsoft SQL Server
C#
HTML
CSS
JavaScript
JQuery
BootStrap
DevExtreme DataGrid

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });       services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
            services.AddDbContext<SchoolCoreDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Student}/{action=List}/{id?}");
            });
        }
    }
 public class SchoolCoreDbContext : DbContext
    {
        public SchoolCoreDbContext(DbContextOptions<SchoolCoreDbContext> options) : base(options)
        {
        }
        public DbSet<Student> Student { get; set; }
    }
[Table("Student")]
    public class Student
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int StudentId { get; set; }

        [Required]
        [MinLength(3)]
        [MaxLength(30)]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required]
        [MinLength(3)]
        [MaxLength(30)]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
    }
public class StudentViewModel
    {
        public Student Student { get; set; }
    }
public class StudentController : Controller
    {
        private readonly SchoolCoreDbContext _dbContext;

        public StudentController(SchoolCoreDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public IActionResult List()
        {
            return View();
        }

        [HttpGet]
        public object GetStudentList(DataSourceLoadOptions loadOptions)
        {
            var lstStudents = _dbContext.Student.ToList();
            var vmStudent = new List<StudentViewModel>();

            foreach (var student in lstStudents)
            {
                vmStudent.Add(new StudentViewModel
                {
                    Student = student
                });
            }
            return vmStudent;
        }

        [HttpPost]
        public IActionResult StudentInsert(string values)
        {
            var vmStudent = new StudentViewModel();
            JsonConvert.PopulateObject(values, vmStudent);

            _dbContext.Student.Add(new Student {
                FirstName = vmStudent.Student.FirstName,
                LastName = vmStudent.Student.LastName
            });
            _dbContext.SaveChanges();
            return RedirectToAction("List");
        }

        [HttpPut]
        public IActionResult StudentUpdate(int key, string values)
        {
            var vmStudent = new StudentViewModel();
            JsonConvert.PopulateObject(values, vmStudent);
            var StudentUpdate = _dbContext.Student.First(s => s.StudentId == key);
            StudentUpdate.FirstName = vmStudent.Student.FirstName;
            StudentUpdate.LastName = vmStudent.Student.LastName;
            _dbContext.Update(StudentUpdate);
            _dbContext.SaveChanges();
            return RedirectToAction("List");
        }
        public IActionResult StudentDelete(int key, DataSourceLoadOptions loadOptions)
        {
            var StudentDelete = _dbContext.Student.First(s => s.StudentId == key);
            _dbContext.Student.Remove(StudentDelete);
            _dbContext.SaveChanges();
            return RedirectToAction("List");
        }
    }
@{
    ViewData["Title"] = "List";
    Layout = "~/Views/Shared/_DashBoard.cshtml";
}
@(Html.DevExtreme().DataGrid<SchoolCore.ViewModels.StudentViewModel>()
        .DataSource(ds => ds.Mvc()
            .Controller("Student")
            .LoadAction("GetStudentList")
            .InsertAction("StudentInsert")
            .UpdateAction("StudentUpdate")
            .DeleteAction("StudentDelete")
            .Key("Student.StudentId")
    )
    .RemoteOperations(true)
    .Columns(columns => {
        columns.AddFor(m => m.Student.StudentId);
        columns.AddFor(m => m.Student.FirstName);
        columns.AddFor(m => m.Student.LastName);
    })
    .Editing(e => e
        .AllowAdding(true)
        .AllowUpdating(true)
        .AllowDeleting(true)
    )
)

Leave a Reply

Your email address will not be published. Required fields are marked *