Dear All I would like to have one view in which I will show listing , I will add new record , I will update and delete record only one signle view I want to show all of them in one view , is there any example for asp.net core mvc ?
Loading
Dear All I would like to have one view in which I will show listing , I will add new record , I will update and delete record only one signle view I want to show all of them in one view , is there any example for asp.net core mvc ?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Abhishek YadavRank #217 · 11.3K reputationPosted Aug 4, 2024, 7:42 AM EDT
Model: Defines the structure of your data.
Controller: Handles the CRUD operations.
Indexreturns the view,Addadds a new item,Updateupdates an existing item, andDeleteremoves an item.Views:
JavaScript: Uses jQuery to send AJAX requests to the server to perform CRUD operations and update the view accordingly.
This approach provides a single-page interface for managing records, improving the user experience by avoiding full page reloads.
Tahir AnsariRank #366 · 6.8K reputationPosted Aug 4, 2024, 9:49 AM EDT
let’s assume you have a
Productmodelpublic class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }Next, create a controller to handle the logic.
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; public class ProductsController : Controller { private static List _products = new List { new Product { Id = 1, Name = "Product1", Price = 10.0m }, new Product { Id = 2, Name = "Product2", Price = 20.0m } }; // GET: Products public IActionResult Index() { return View(_products); } // POST: Products/Add [HttpPost] public IActionResult Add(Product product) { if (ModelState.IsValid) { product.Id = _products.Max(p => p.Id) + 1; _products.Add(product); } return RedirectToAction(nameof(Index)); } // POST: Products/Update [HttpPost] public IActionResult Update(Product product) { if (ModelState.IsValid) { var existingProduct = _products.FirstOrDefault(p => p.Id == product.Id); if (existingProduct != null) { existingProduct.Name = product.Name; existingProduct.Price = product.Price; } } return RedirectToAction(nameof(Index)); } // POST: Products/Delete [HttpPost] public IActionResult Delete(int id) { var product = _products.FirstOrDefault(p => p.Id == id); if (product != null) { _products.Remove(product); } return RedirectToAction(nameof(Index)); } }Now, create a view to handle all actions in a single page.
Index.cshtml
@model IEnumerable @{ ViewData["Title"] = "Product Management"; } Product Management Add Product Name: Price: Add Update Product Name: Price: Update Delete Product Product Id: Delete Product List ID Name Price @foreach (var product in Model) { @product.Id @product.Name @product.Price }Mark TaborRank #914 · 2.3K reputationPosted Aug 4, 2024, 11:53 AM EDT
The issue is i am using viewmodel and let say I have two models student and courses as below
public class student
{
public int id {get;set;}
public string name{get;set;}
}
public class coruse
{
public int id {get;set;}
public string name{get;set;}
}
My ViewModel is like below
public class MyVM
{
public student stu{get;set;}
public course cur{get;set;}
}
my index view need List and List and my create view does not need list so if we put all of them in one view how I adjust my model like for create it shoud not be list and for lising it should be list . to it but when I render the view it says the main view in which I have parital view does not have Ieneumerable or list so the partial view should have the same model as the main view have. thats the problem any example here
Abhishek Yadav yes I have a partial view and for listing and I give model as List
Jignesh KumarRank #91 · 22.9K reputationPosted Aug 6, 2024, 12:44 AM EDT
Hey Mark,
Please use this example,
Create model for student, Course and StudentCourse mapper calss and view model
public class Student { public int Id { get; set; } public string Name { get; set; } public List StudentCourses { get; set; } } public class Course { public int Id { get; set; } public string Title { get; set; } public List StudentCourses { get; set; } } // Student course mapper class public class StudentCourse { public int StudentId { get; set; } public Student Student { get; set; } public int CourseId { get; set; } public Course Course { get; set; } } // View Model for Student course public class StudentCourseViewModel { public Student Student { get; set; } public List AvailableCourses { get; set; } public List SelectedCourseIds { get; set; } = new List(); }Create Controller :
// Controllers/StudentController.cs public class StudentController : Controller { private readonly ApplicationDbContext _context; public StudentController(ApplicationDbContext context) { _context = context; } public async Task Index() { var students = await _context.Students.Include(s => s.StudentCourses).ThenInclude(sc => sc.Course).ToListAsync(); return View(students); } public IActionResult Create() { var viewModel = new StudentCourseViewModel { AvailableCourses = _context.Courses.ToList() }; return View(viewModel); } [HttpPost] public async Task Create(StudentCourseViewModel viewModel) { if (ModelState.IsValid) { var student = new Student { Name = viewModel.Student.Name, StudentCourses = viewModel.SelectedCourseIds.Select(courseId => new StudentCourse { CourseId = courseId }).ToList() }; _context.Students.Add(student); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } viewModel.AvailableCourses = _context.Courses.ToList(); return View(viewModel); } public async Task Edit(int id) { var student = await _context.Students.Include(s => s.StudentCourses).ThenInclude(sc => sc.Course).FirstOrDefaultAsync(s => s.Id == id); if (student == null) return NotFound(); var viewModel = new StudentCourseViewModel { Student = student, AvailableCourses = _context.Courses.ToList(), SelectedCourseIds = student.StudentCourses.Select(sc => sc.CourseId).ToList() }; return View(viewModel); } [HttpPost] public async Task Edit(StudentCourseViewModel viewModel) { if (ModelState.IsValid) { var student = await _context.Students.Include(s => s.StudentCourses).FirstOrDefaultAsync(s => s.Id == viewModel.Student.Id); if (student == null) return NotFound(); student.Name = viewModel.Student.Name; var existingCourseIds = student.StudentCourses.Select(sc => sc.CourseId).ToList(); var newCourseIds = viewModel.SelectedCourseIds; var coursesToRemove = student.StudentCourses.Where(sc => !newCourseIds.Contains(sc.CourseId)).ToList(); var coursesToAdd = newCourseIds.Where(id => !existingCourseIds.Contains(id)).Select(id => new StudentCourse { StudentId = student.Id, CourseId = id }).ToList(); _context.StudentCourses.RemoveRange(coursesToRemove); _context.StudentCourses.AddRange(coursesToAdd); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } viewModel.AvailableCourses = _context.Courses.ToList(); return View(viewModel); } public async Task Delete(int id) { var student = await _context.Students.FindAsync(id); if (student == null) return NotFound(); _context.Students.Remove(student); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } }Create View :
@model IEnumerable Students Name Courses @foreach (var student in Model) { @student.Name @foreach (var course in student.StudentCourses.Select(sc => sc.Course)) { @course.Title } Edit Delete } Add New StudentEdit View
@model StudentCourseViewModel @(Model.Student.Id == 0 ? "Create Student" : "Edit Student") Courses Save