ASP.net mvc create a new data does not work - c#

when i try to create a new data from the form and i do not get any error and the page just refresh , without creating any new data . im using sql server and i have a ForeignKey from another table.
my course controller:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using SchoolGrades.Models;
namespace SchoolGrades.Controllers { public class CoursesController : Controller { private readonly UniDBContext _context;
public CoursesController(UniDBContext context)
{
_context = context;
}
// GET: Courses
public async Task<IActionResult> Index()
{
var uniDBContext = _context.Courses.Include(c => c.ProfessorsAfmNavigation);
return View(await uniDBContext.ToListAsync());
}
// GET: Courses/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null || _context.Courses == null)
{
return NotFound();
}
var course = await _context.Courses
.Include(c => c.ProfessorsAfmNavigation)
.FirstOrDefaultAsync(m => m.IdCourse == id);
if (course == null)
{
return NotFound();
}
return View(course);
}
// GET: Courses/Create
public IActionResult Create()
{
ViewData["ProfessorsAfm"] = new SelectList(_context.Professors, "Afm", "Afm");
return View();
}
// POST: Courses/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("IdCourse,CourseTitle,CourseSemester,ProfessorsAfm")] Course course)
{
if (ModelState.IsValid)
{
_context.Add(course);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["ProfessorsAfm"] = new SelectList(_context.Professors, "Afm", "Afm", course.ProfessorsAfm);
return View(course);
}
// GET: Courses/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null || _context.Courses == null)
{
return NotFound();
}
var course = await _context.Courses.FindAsync(id);
if (course == null)
{
return NotFound();
}
ViewData["ProfessorsAfm"] = new SelectList(_context.Professors, "Afm", "Afm", course.ProfessorsAfm);
return View(course);
}
// POST: Courses/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, [Bind("IdCourse,CourseTitle,CourseSemester,ProfessorsAfm")] Course course)
{
if (id != course.IdCourse)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(course);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CourseExists(course.IdCourse))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["ProfessorsAfm"] = new SelectList(_context.Professors, "Afm", "Afm", course.ProfessorsAfm);
return View(course);
}
// GET: Courses/Delete/5
public async Task<IActionResult> Delete(string id)
{
if (id == null || _context.Courses == null)
{
return NotFound();
}
var course = await _context.Courses
.Include(c => c.ProfessorsAfmNavigation)
.FirstOrDefaultAsync(m => m.IdCourse == id);
if (course == null)
{
return NotFound();
}
return View(course);
}
// POST: Courses/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
if (_context.Courses == null)
{
return Problem("Entity set 'UniDBContext.Courses' is null.");
}
var course = await _context.Courses.FindAsync(id);
if (course != null)
{
_context.Courses.Remove(course);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool CourseExists(string id)
{
return (_context.Courses?.Any(e => e.IdCourse == id)).GetValueOrDefault();
}
}
}
`
my course model:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore;
namespace SchoolGrades.Models;
[Table("course")] public partial class Course { [Key] [Column("idCOURSE")] [StringLength(25)] [Unicode(false)] public string IdCourse { get; set; } = null!;
[StringLength(60)]
[Unicode(false)]
public string CourseTitle { get; set; } = null!;
[StringLength(25)]
[Unicode(false)]
public string CourseSemester { get; set; } = null!;
[Column("PROFESSORS_AFM")]
[StringLength(25)]
[Unicode(false)]
public string ProfessorsAfm { get; set; } = null!;
[InverseProperty("CourseIdCourseNavigation")]
public virtual CourseHasStudent? CourseHasStudent { get; set; }
[ForeignKey("ProfessorsAfm")]
[InverseProperty("Courses")]
public virtual Professor ProfessorsAfmNavigation { get; set; } = null!;
}
and course create view :
#model SchoolGrades.Models.Course
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Course</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="IdCourse" class="control-label"></label>
<input asp-for="IdCourse" class="form-control" />
<span asp-validation-for="IdCourse" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CourseTitle" class="control-label"></label>
<input asp-for="CourseTitle" class="form-control" />
<span asp-validation-for="CourseTitle" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CourseSemester" class="control-label"></label>
<input asp-for="CourseSemester" class="form-control" />
<span asp-validation-for="CourseSemester" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ProfessorsAfm" class="control-label"></label>
<select asp-for="ProfessorsAfm" class ="form-control" asp-items="ViewBag.ProfessorsAfm"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
i removed the if statement from the course controller .
if (ModelState.IsValid)
{ _context.Add(course);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
and i kept it like this and it worked and i could create a new data in the table after i removed the if statement .
_context.Add(course);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
any other solutions please.

Related

Select multiple and display corresponding value from another model

I have Two different ASP.net Core 6.0 applications running that have tables linked to other tables by foreign keys. I create a CRUD for both pages. At the first CRUD (PriceList) page, I will enter the data. At the the second CRUD (CombineStage) of the page I will get the data (Stage) from the first page (Pricelist) using multiple select and the search box and its corresponding price in the Index page after using multiple select. I can't find any code commands to make this work. Any help would be appreciated. My foreign key is PricelistId. Below is my code:
CombineStage.cs
using System.ComponentModel.DataAnnotations;
namespace WebApp.Models
{
public class CombineStage
{
[Key]
public int StageId { get; set; }
[Required(ErrorMessage = "Bạn chưa nhập tên công đoạn")]
public string Name { get; set; }
[Required(ErrorMessage = "Bạn chưa chọn công đoạn")]
public int PricelistId { get; set; }
[Required(ErrorMessage = "Bạn chưa chọn ảnh")]
public string Picture { get; set; }
[Required(ErrorMessage = "Bạn chưa nhập giá tiền")]
public int Price { get; set; }
public virtual PriceList PriceList { get; set; }
}
}
CombineStagesController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WebApp.Models;
namespace WebApp.Areas.Admin.Controllers
{
[Area("Admin")]
public class CombineStagesController : Controller
{
private readonly ManageContext _context;
public CombineStagesController(ManageContext context)
{
_context = context;
}
// GET: Admin/CombineStages
public async Task<IActionResult> Index()
{
var manageContext = _context.CombineStage.Include(c => c.PriceList);
return View(await manageContext.ToListAsync());
}
// GET: Admin/CombineStages/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null || _context.CombineStage == null)
{
return NotFound();
}
var combineStage = await _context.CombineStage
.Include(c => c.PriceList)
.FirstOrDefaultAsync(m => m.StageId == id);
if (combineStage == null)
{
return NotFound();
}
return View(combineStage);
}
// GET: Admin/CombineStages/Create
public IActionResult Create()
{
ViewData["PricelistId"] = new SelectList(_context.PriceLists, "PricelistId", "Stage");
return View();
}
// POST: Admin/CombineStages/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("StageId,Name,PricelistId,Picture,Price")] CombineStage combineStage)
{
if (ModelState.IsValid)
{
_context.Add(combineStage);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["PricelistId"] = new SelectList(_context.PriceLists, "PricelistId", "Stage", combineStage.PricelistId);
return View(combineStage);
}
// GET: Admin/CombineStages/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null || _context.CombineStage == null)
{
return NotFound();
}
var combineStage = await _context.CombineStage.FindAsync(id);
if (combineStage == null)
{
return NotFound();
}
ViewData["PricelistId"] = new SelectList(_context.PriceLists, "PricelistId", "Stage", combineStage.PricelistId);
return View(combineStage);
}
// POST: Admin/CombineStages/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("StageId,Name,PricelistId,Picture,Price")] CombineStage combineStage)
{
if (id != combineStage.StageId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(combineStage);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CombineStageExists(combineStage.StageId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["PricelistId"] = new SelectList(_context.PriceLists, "PricelistId", "Stage", combineStage.PricelistId);
return View(combineStage);
}
// GET: Admin/CombineStages/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null || _context.CombineStage == null)
{
return NotFound();
}
var combineStage = await _context.CombineStage
.Include(c => c.PriceList)
.FirstOrDefaultAsync(m => m.StageId == id);
if (combineStage == null)
{
return NotFound();
}
return View(combineStage);
}
// POST: Admin/CombineStages/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
if (_context.CombineStage == null)
{
return Problem("Entity set 'ManageContext.CombineStage' is null.");
}
var combineStage = await _context.CombineStage.FindAsync(id);
if (combineStage != null)
{
_context.CombineStage.Remove(combineStage);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool CombineStageExists(int id)
{
return _context.CombineStage.Any(e => e.StageId == id);
}
}
}
Create
#model WebApp.Models.CombineStage
#{
ViewData["Title"] = "Create";
Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
}
<h1>Create</h1>
<h4>CombineStage</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<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="PricelistId" class="control-label"></label>
<select asp-for="PricelistId" class ="form-control" asp-items="ViewBag.PricelistId" multiple>
</select>
</div>
<div class="form-group">
<label asp-for="Picture" class="control-label"></label>
<input asp-for="Picture" class="form-control" />
<span asp-validation-for="Picture" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
Thank you so much!
Update Pricelist:
Pricelist.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
namespace WebApp.Models
{
public partial class PriceList
{
public PriceList()
{
StageDetails = new HashSet<StageDetail>();
CombineStages = new HashSet<CombineStage>();
}
[Key]
public int PricelistId { get; set; }
[Required(ErrorMessage = "Bạn chưa chọn ảnh")]
public string Image { get; set; }
[Required (ErrorMessage = "Bạn chưa chọn máy may")]
public Machine Machine { get; set; }
[Required (ErrorMessage = "Bạn chưa tên nhập công đoạn")]
public string Stage { get; set; }
[Required (ErrorMessage = "Bạn chưa nhập giá tiền")]
public int Price { get; set; }
public virtual ICollection<StageDetail> StageDetails { get; set; }
public virtual ICollection<CombineStage> CombineStages { get; set; }
}
public enum Machine
{
VS,
[Display(Name = "1K")]
OneK
}
}
PriceListsController
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WebApp.Models;
using WebApp.ViewModel;
namespace WebApp.Areas.Admin.Controllers
{
[Area("Admin")]
public class PriceListsController : Controller
{
private readonly ManageContext _context;
private readonly IWebHostEnvironment _environment;
public PriceListsController(ManageContext context, IWebHostEnvironment environment)
{
_context = context;
_environment = environment;
}
public async Task<IActionResult> Index()
{
return View(await _context.PriceLists.ToListAsync());
}
public async Task<IActionResult> Details(int? id)
{
try
{
if (id == null)
{
return NotFound();
}
var priceList = await _context.PriceLists
.FirstOrDefaultAsync(m => m.PricelistId == id);
var priceListModelView = new PriceListViewModel()
{
Id = priceList.PricelistId,
ExistingImage = priceList.Image,
Machine = priceList.Machine,
Stage = priceList.Stage,
Price = priceList.Price
};
if (priceList == null)
{
return NotFound();
}
return View(priceList);
}
catch (Exception)
{
throw;
}
}
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(PriceListViewModel model)
{
try
{
if (ModelState.IsValid)
{
string uniqueFileName = ProcessUploadedFile(model);
PriceList priceList = new()
{
Image = uniqueFileName,
Machine = model.Machine,
Stage = model.Stage,
Price = model.Price
};
_context.Add(priceList);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
catch (Exception)
{
throw;
}
return View(model);
}
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var priceList = await _context.PriceLists.FindAsync(id);
var priceListViewModel = new PriceListViewModel()
{
Id = priceList.PricelistId,
ExistingImage = priceList.Image,
Machine = priceList.Machine,
Stage = priceList.Stage,
Price = priceList.Price
};
if (priceList == null)
{
return NotFound();
}
return View(priceListViewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, PriceListViewModel model)
{
if (ModelState.IsValid)
{
var priceList = await _context.PriceLists.FindAsync(model.Id);
priceList.Machine = model.Machine;
priceList.Stage = model.Stage;
priceList.Price = model.Price;
if (model.PricelistImage != null)
{
if (model.ExistingImage != null)
{
string filePath = Path.Combine(_environment.WebRootPath, "Images", model.ExistingImage);
System.IO.File.Delete(filePath);
}
priceList.Image = ProcessUploadedFile(model);
}
_context.Update(priceList);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View();
}
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var priceList = await _context.PriceLists
.FirstOrDefaultAsync(m => m.PricelistId == id);
var priceListViewModel = new PriceListViewModel()
{
Id = priceList.PricelistId,
ExistingImage = priceList.Image,
Machine = priceList.Machine,
Stage = priceList.Stage,
Price = priceList.Price
};
if (priceList == null)
{
return NotFound();
}
return View(priceListViewModel);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var priceList = await _context.PriceLists.FindAsync(id);
//string deleteFileFromFolder = "wwwroot\\Uploads\\";
string deleteFileFromFolder = Path.Combine(_environment.WebRootPath, "Images");
var CurrentImage = Path.Combine(Directory.GetCurrentDirectory(), deleteFileFromFolder, priceList.Image);
_context.PriceLists.Remove(priceList);
if (System.IO.File.Exists(CurrentImage))
{
System.IO.File.Delete(CurrentImage);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool SpeakerExists(int id)
{
return _context.PriceLists.Any(e => e.PricelistId == id);
}
private string ProcessUploadedFile(PriceListViewModel model)
{
string uniqueFileName = null;
string path = Path.Combine(_environment.WebRootPath, "Images");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (model.PricelistImage != null)
{
string uploadsFolder = Path.Combine(_environment.WebRootPath, "Images");
uniqueFileName = Guid.NewGuid().ToString() + "_" + model.PricelistImage.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
model.PricelistImage.CopyTo(fileStream);
}
}
return uniqueFileName;
}
}
}
Update Create(HTTPPost) CombineStagesController:
(But it still hasn't solved my request. I want when I select multiple then I get the entire corresponding Price value in Index Page)
public IActionResult Create()
{
ViewData["PricelistId"] = new SelectList(_context.PriceLists, "PricelistId", "Stage");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("StageId,Name,PricelistId,Picture,Price")] CombineStage combineStage, int[] PricelistId)
{
foreach (var id in PricelistId)
{
var stage = _context.PriceLists.Where(m => m.PricelistId == id).Select(x => x.Stage).ToString();
}
if (ModelState.IsValid)
{
_context.Add(combineStage);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(combineStage);
}
Update
Things I'm looking forward to
Next I will choose 2 option stages that I created
Next step, I want the total price of the 2 process options I have selected here
Finally, I want to show all the stages and prices of my 2 options that I have selected
That's all my request.
It's not entirely clear what you're expected result is with regard to records and their respective prices, but the binding code in your Create(CombinedStage, int[]) appears problematic given the PricelistId binding to CombinedStage. I would suggest creating a view model that reflects the form elements with an array/collection of simple values for PriceListIds in order for <select multiple>. For example, the new CombinedStageViewModel posted to the Create should have a property for `PricelistIds' such as the following for :
public IEnumerable<int> PricelistIds { get; set; }
Again, it's not entirely clear from the provided sample code or the accompanying description of the problem what the desired behavior is with respect to getting "...the entire corresponding Price value in Index Page." If you can post a sample project and define the expected results, it would make it much easier to provide a comprehensive answer to your question.
I made a simple test, you can refer to it.
I added a field to CombineStage to store your options:
public class CombineStage
{
[Key]
[ForeignKey("StageId")]
public int StageId { get; set; }
[Required(ErrorMessage = "Bạn chưa nhập tên công đoạn")]
public string Name { get; set; }
[Required(ErrorMessage = "Bạn chưa chọn công đoạn")]
[ForeignKey("PricelistId")]
public int PricelistId { get; set; }
[Required(ErrorMessage = "Bạn chưa chọn ảnh")]
public string Picture { get; set; }
[Required(ErrorMessage = "Bạn chưa nhập giá tiền")]
public int Price { get; set; }
public string PricelistIdList { get; set; }
public virtual PriceList PriceList { get; set; }
}
CombineStagesController:
public class CombineStagesController : Controller
{
private readonly ManageContext _context;
public CombineStagesController(ManageContext context)
{
_context = context;
}
// GET: Admin/CombineStages
public async Task<IActionResult> Index()
{
var manageContext = _context.CombineStage.Include(c => c.PriceList);
return View(await manageContext.ToListAsync());
}
// GET: Admin/CombineStages/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null || _context.CombineStage == null)
{
return NotFound();
}
var combineStage = await _context.CombineStage
.Include(c => c.PriceList)
.FirstOrDefaultAsync(m => m.StageId == id);
int[] PriceIdList = combineStage.PricelistIdList.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
List<PriceList> priceLists = new List<PriceList>();
foreach(var PriceId in PriceIdList)
{
var PriceDetails = _context.PriceLists.Where(c => c.PricelistId == PriceId).FirstOrDefault();
priceLists.Add(PriceDetails);
}
ViewBag.priceLists = priceLists;
if (combineStage == null)
{
return NotFound();
}
return View(combineStage);
}
// GET: Admin/CombineStages/Create
public IActionResult Create()
{
var priceLists = _context.PriceLists.ToList();
List<SelectListItem> mylist = new List<SelectListItem>();
foreach (var price in priceLists)
{
mylist.Add(new SelectListItem { Text = price.Stage, Value = price.PricelistId.ToString() });
}
ViewBag.PricelistId = mylist;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Name,PricelistId,Picture,Price,PriceList")] CombineStage combineStage, int[] PricelistId)
{
int price = 0;
var stage = "";
PriceList priceList = new PriceList();
foreach (var id in PricelistId)
{
stage = _context.PriceLists.Where(m => m.PricelistId == id).FirstOrDefault().Stage.ToString();
price += _context.PriceLists.Where(m => m.PricelistId == id).FirstOrDefault().Price;
priceList = _context.PriceLists.Where(m => m.PricelistId == id).FirstOrDefault();
}
combineStage.Price = price;
combineStage.PriceList = priceList;
combineStage.PricelistIdList = string.Join(",", PricelistId);
ModelState.Clear();
if (TryValidateModel(combineStage))
{
_context.Add(combineStage);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(combineStage);
}
}
Create.cshtml:
#model _2022092602.Models.CombineStage
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>CombineStage</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<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="PricelistId" class="control-label"></label>
<select asp-for="PricelistId" class ="form-control" asp-items="#ViewBag.PricelistId" multiple>
</select>
</div>
<div class="form-group">
<label asp-for="Picture" class="control-label"></label>
<input asp-for="Picture" class="form-control" />
<span asp-validation-for="Picture" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
Details.cshtml:
#model _2022092602.Models.CombineStage
<div>#Model.Name</div>
<div>#Model.Picture</div>
<div>#Model.Price</div>
<div>
#foreach (var price in ViewBag.priceLists)
{
<div>
<span>#price.PricelistId</span>
<span>#price.Price</span>
<span>#price.Stage</span>
</div>
}
</div>
Test Result:

How to Get Selected List of DropDownList from Database or Model and Populate in Dropdown on View

I am performing a Bitwise-Create operation on my modal(view) and I am to select a dropdown list of users from another table/model and bind to the view so I can forward the request to them. I want to select users based on a certain role, if possible: but I just want to select the users from the database table.
If you need any other model or controller, kindly prompt me so i add it.
Please help..
Below is my Code:
Cshtml Code for the Modal View:(Removed Other TextFields):
So where I have the select tags, i want to get the select list of users and add it.
<div class="row">
<div class="col-md-12">
<form asp-action="AddOrEdit" asp-route-id="#Model.BitwiseId" autocomplete="false" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="col-md-6">
<div class="form-group">
<label asp-for="AccountName" class="control-label"></label>
<input asp-for="AccountName" class="form-control" />
<span asp-validation-for="AccountName" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="File" class="control-label"></label>
<input type="file" name="userfile" class="form-control" accept=".xlsx"/>
<span asp-validation-for="File" class="text-danger"></span>
</div>
<div class="form-group">
<label for="cars">Select 1st Approver </label>
<select name="group_heads" id="group_heads" class="form-control">
<option value="">Select</option>
<option value="2">Bobby</option>
</select>
</div>
<hr />
<div class="d-grid gap-2">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
Code: Controller for the Bitwise - Add Method:
namespace BOGBitwiseApp.Controllers
{
public class BitwiseController : Controller
{
private readonly ApplicationDbContext _context;
public BitwiseController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
return View(await _context.Bitwises.ToListAsync());
}
// GET: Transaction/AddOrEdit(Insert)
// GET: Transaction/AddOrEdit/5(Update)
[NoDirectAccess]
public async Task<IActionResult> AddOrEdit(int id = 0)
{
if (id == 0)
return View(new BitwiseModel());
else
{
var bitwiseModel = await _context.Bitwises.FindAsync(id);
if (bitwiseModel == null)
{
return NotFound();
}
return View(bitwiseModel);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddOrEdit(int id, [Bind("BitwiseId,..., Amount")] BitwiseModel bitwiseModel, ...)
{
if (ModelState.IsValid)
{
//New
if (id == 0)
{
string filename = userfile.FileName;
...
await userfile.CopyToAsync(stream);
var data = _context.Users.ToListAsync();
bitwiseModel.Date = DateTime.Now;
_context.Add(bitwiseModel);
await _context.SaveChangesAsync();
}
//Update
else
{
try
{
_context.Update(bitwiseModel);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BitwiseModelExists(bitwiseModel.BitwiseId))
{ return NotFound(); }
else
{ throw; }
}
}
return Json(new { isValid = true, html = Helper.RenderRazorViewToString(this, "_ViewAll", _context.Bitwises.ToList()) });
}
return Json(new { isValid = false, html = Helper.RenderRazorViewToString(this, "AddOrEdit", bitwiseModel) });
}
Model Code for Bitwise (Add):
public class BitwiseModel
{
[Key]
public int BitwiseId { get; set; }
[Required]
[Column(TypeName = "nvarchar(100)")]
[DisplayName("Customer Name")]
public string AccountName { get; set; }
[NotMapped]
[DisplayName("Invoice File")]
public IFormFile? File { get; set; }
}
**Model for Users Table:**
public class ApplicationUser : IdentityUser
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
public int UsernameChangeLimit { get; set; } = 2;
public byte[]? ProfilePicture { get; set; }
}

Custom Validation Attribute not working in .NET 6

I have a model where I am trying to implement conditional validation. My few properties will be required only if the value for those properties are true in some other collection. I found some code here Conditional validation in MVC.NET Core (RequiredIf) but I am not understanding why it is not working in my case.
Expected case is, the validation should fire for "FirstName" field as it has true value in the collection and should not fire for Last Name field as it has false value in the collection. Currently validation is not firing at all for FirstName.
Here is my code:
Person.cs
public class Person
{
public int Id { get; set; }
//This property should be required only when this property exist in below class RequiredFieldsData.PropertiesPair() collection and has value true
[RequiredIf("FirstName", true, ErrorMessage = "First Name is required")]
public string FirstName { get; set; }
[RequiredIf("LastName", true, ErrorMessage ="Last name is required")]
public string LastName { get; set; }
}
public static class RequiredFieldsData
{
public static Dictionary<string, bool> PropertiesPair()
{
return new Dictionary<string, bool>
{
{"FirstName", true},
{"LastName", false }
};
}
}
[AttributeUsage(AttributeTargets.Property)]
public class RequiredIfAttribute : ValidationAttribute, IClientModelValidator
{
private string PropertyName { get; set; }
private bool DesiredValue { get; set; }
public RequiredIfAttribute(string propertyName, bool desiredValue)
{
PropertyName = propertyName;
DesiredValue = desiredValue;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
object instance = context.ObjectInstance;
Type type = instance.GetType();
bool propertyValue = RequiredFieldsData.PropertiesPair().Any(t => t.Key == type.GetProperty(PropertyName).Name && t.Value == DesiredValue);
if (propertyValue && string.IsNullOrWhiteSpace(value?.ToString()))
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-requiredif", errorMessage);
}
private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
PersonController.cs
public class PersonController : Controller
{
// GET: PersonController
public ActionResult Index()
{
List<Person> list = new List<Person>
{
new Person
{
Id=1,
FirstName ="Ashwani",
LastName ="Singh"
}
};
return View(list);
}
// GET: PersonController/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: PersonController/Create
public ActionResult Create()
{
return View();
}
// POST: PersonController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Person personModel)
{
try
{
if(ModelState.IsValid)
return RedirectToAction(nameof(Index));
return null;
}
catch
{
return View();
}
}
// GET: PersonController/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: PersonController/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: PersonController/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: PersonController/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
}
Create.cshtml
#model Test.Models.Person
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Person</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Id" class="control-label"></label>
<input asp-for="Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
My project is in .NET 6 MVC.
Can anybody tell me where I am going wrong. Thank You

uploading image Asp.net core 3.1 with postgresql

I'm trying to upload a image in asp .NET core. I could not upload the image.
There is no error message. all are work correctly without uploading the image.
anyone tell me what is problem in these codes
also I have a folder "Uploads" in the wwwroot folder.
I attach my codes below.
This is my Create.cshtml
#model WebApplication1.ViewModels.EmployeeViewModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Employee</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create" enctype="multipart/form-data ">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="EmployeeName" class="control-label"></label>
<input asp-for="EmployeeName" class="form-control" />
<span asp-validation-for="EmployeeName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EmployeeProfile" class="control-label"></label>
<div class="custom-file">
<input type="file" asp-for="EmployeeProfile" class="custom-file-input" />
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<span asp-validation-for="EmployeeProfile" class="text-danger"></span>
#*<label asp-for="EmployeeImage" class="control-label"></label>
<input asp-for="EmployeeImage" class="form-control" />
<span asp-validation-for="EmployeeImage" class="text-danger"></span>*#
</div>
<div class="form-group">
<label asp-for="DepartmentId" class="control-label"></label>
<select asp-for="DepartmentId" class="form-control" asp-items="ViewBag.DepartmentId"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-sm btn-primary rounded-0" />
<a asp-action="Index" class="btn btn-sm btn-primary rounded-0">Back to List</a>
#*<a asp-action="Index">Back to List</a>*#
</div>
</form>
</div>
</div>
#section Scripts {
<script>
// Add the following code if you want the name of the file appear on select
$(".custom-file-input").on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
</script>
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
this is my EmployeesController
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WebApplication1.Models;
using WebApplication1.ViewModels;
namespace WebApplication1.Controllers
{
public class EmployeesController : Controller
{
private readonly EmployeeDbContext _context;
private readonly IWebHostEnvironment webHostEnvironment;
public EmployeesController(EmployeeDbContext context, IWebHostEnvironment hostEnvironment)
{
_context = context;
webHostEnvironment = hostEnvironment;
}
// GET: Employees
//public async Task<IActionResult> Index()
//{
// var employeeDbContext = _context.Employees.Include(e => e.Department);
// return View(await employeeDbContext.ToListAsync());
//}
public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? pageNumber)
{
ViewData["CurrentSort"] = sortOrder;
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
if (searchString != null)
{
pageNumber = 1;
}
else
{
searchString = currentFilter;
}
//var employeeDbContext = _context.Employees.Include(e => e.Department);
ViewData["CurrentFilter"] = searchString;
var employee = from em in _context.Employees.Include(e => e.Department)
select em;
// var employee = from e in _context.Employees
if (!String.IsNullOrEmpty(searchString))
{
employee = employee.Where(em => em.EmployeeName.Contains(searchString)
|| em.EmployeeName.Contains(searchString));
}
switch (sortOrder)
{
case "name_desc":
employee = employee.OrderByDescending(em => em.EmployeeName);
break;
default:
employee = employee.OrderBy(em => em.EmployeeName);
break;
}
int pageSize = 3;
return View(await PaginatedList<Employee>.CreateAsync(employee.AsNoTracking(), pageNumber ?? 1, pageSize));
//return View(await _context.Departments.ToListAsync());
}
// GET: Employees/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var employee = await _context.Employees
.Include(e => e.Department)
.FirstOrDefaultAsync(m => m.Id == id);
var EmployeeViewModel = new EmployeeViewModel()
{
Id = employee.Id,
EmployeeName = employee.EmployeeName,
DepartmentId = employee.DepartmentId,
ExistingImage = employee.EmployeeImage
};
if (employee == null)
{
return NotFound();
}
return View(employee);
}
// GET: Employees/Create
public IActionResult Create()
{
ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "departmentName");
return View();
}
// POST: Employees/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("EmployeeName,EmployeeImage,DepartmentId")] EmployeeViewModel model)
{
if (ModelState.IsValid)
{
string uniqueFileName = ProcessUploadedFile(model);
Employee employee = new Employee
{
EmployeeName = model.EmployeeName,
DepartmentId = model.DepartmentId,
EmployeeImage = uniqueFileName
};
_context.Add(employee);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "departmentName", model.DepartmentId);
return View(model);
}
// GET: Employees/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var employee = await _context.Employees.FindAsync(id);
var EmployeeViewModel = new EmployeeViewModel()
{
Id = employee.Id,
EmployeeName = employee.EmployeeName,
DepartmentId = employee.DepartmentId,
ExistingImage = employee.EmployeeImage
}; if (employee == null)
{
return NotFound();
}
ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "departmentName", employee.DepartmentId);
return View(EmployeeViewModel);
}
// POST: Employees/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,EmployeeName,EmployeeImage,DepartmentId")] EmployeeViewModel model)
{
if (id != model.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
var employee = await _context.Employees.FindAsync(model.Id);
employee.EmployeeName = model.EmployeeName;
employee.DepartmentId = model.DepartmentId;
if (model.EmployeeProfile != null)
{
if (model.ExistingImage != null)
{
string filePath = Path.Combine(webHostEnvironment.WebRootPath, "Uploads", model.ExistingImage);
System.IO.File.Delete(filePath);
}
employee.EmployeeImage = ProcessUploadedFile(model);
}
_context.Update(employee);
await _context.SaveChangesAsync();
//try
//{
// _context.Update(model);
// await _context.SaveChangesAsync();
//}
//catch (DbUpdateConcurrencyException)
//{
// if (!EmployeeExists(model.Id))
// {
// return NotFound();
// }
// else
// {
// throw;
// }
//}
return RedirectToAction(nameof(Index));
}
ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "departmentName", model.DepartmentId);
return View();
}
// GET: Employees/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var employee = await _context.Employees
.Include(e => e.Department)
.FirstOrDefaultAsync(m => m.Id == id);
var EmployeeViewModel = new EmployeeViewModel()
{
Id = employee.Id,
EmployeeName = employee.EmployeeName,
DepartmentId = employee.DepartmentId,
ExistingImage = employee.EmployeeImage
};
if (employee == null)
{
return NotFound();
}
return View(EmployeeViewModel);
}
// POST: Employees/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var employee = await _context.Employees.FindAsync(id);
var CurrentImage = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\Uploads", employee.EmployeeImage);
_context.Employees.Remove(employee);
if (await _context.SaveChangesAsync() > 0)
{
if (System.IO.File.Exists(CurrentImage))
{
System.IO.File.Delete(CurrentImage);
}
}
return RedirectToAction(nameof(Index));
}
private bool EmployeeExists(int id)
{
return _context.Employees.Any(e => e.Id == id);
}
private string ProcessUploadedFile(EmployeeViewModel model)
{
string uniqueFileName = null;
if (model.EmployeeProfile != null)
{
string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Uploads");
// uniqueFileName = Guid.NewGuid().ToString() + "_" + model.EmployeeProfile.FileName;
uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.EmployeeProfile.FileName);
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
model.EmployeeProfile.CopyTo(fileStream);
}
}
return uniqueFileName;
}
}
}
This is ProcessUploadedFile method
private string ProcessUploadedFile(EmployeeViewModel model)
{
string uniqueFileName = null;
if (model.EmployeeProfile != null)
{
string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Uploads");
// uniqueFileName = Guid.NewGuid().ToString() + "_" + model.EmployeeProfile.FileName;
uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.EmployeeProfile.FileName);
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
model.EmployeeProfile.CopyTo(fileStream);
}
}
return uniqueFileName;
}
i have 3 viewmodels, see below
EmployeeViewModel
EditImageViewModel
UploadImageViewModel
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;
using WebApplication1.ViewModels;
namespace WebApplication1.ViewModels
{
public class EmployeeViewModel : EditImageViewModel
{
[Required(ErrorMessage = "Please enter Employee Name")]
public string EmployeeName { get; set; }
// Navigation Properties
public int? DepartmentId { get; set; }
public Department Department { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.ViewModels
{
public class EditImageViewModel : UploadImageViewModel
{
public int Id { get; set; }
public string ExistingImage { get; set; }
}
}
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.ViewModels
{
public class UploadImageViewModel
{
[Required(ErrorMessage = "Please choose profile image")]
[Display(Name = "Profile Picture")]
public IFormFile EmployeeProfile { get; set; }
}
}
You have commented out the EmployeeImage, you only passed the EmployeeProfile to action, but
you didn't bind the EmployeeProfile.
Change to this:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("EmployeeName,EmployeeProfile,//***others")] EmployeeViewModel model)
Then I can upload the file using your code.
The [Bind] specifies which properties of a model should be included in model binding.Check:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-5.0#bind-attribute
whole code:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("EmployeeName,EmployeeProfile")] EmployeeViewModel model)
{
if (ModelState.IsValid)
{
string uniqueFileName = ProcessUploadedFile(model);
Employee employee = new Employee
{
EmployeeName = model.EmployeeName,
EmployeeImage = uniqueFileName
};
_context.Add(employee);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return RedirectToAction("Index");
}
private string ProcessUploadedFile(EmployeeViewModel model)
{
string uniqueFileName = null;
if (model.EmployeeProfile != null)
{
string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Uploads");
// uniqueFileName = Guid.NewGuid().ToString() + "_" + model.EmployeeProfile.FileName;
uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.EmployeeProfile.FileName);
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
model.EmployeeProfile.CopyTo(fileStream);
}
}
return uniqueFileName;
}
Create.cshtml:
<div class="row">
<div class="col-md-4">
<form asp-action="Create" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="EmployeeName" class="control-label"></label>
<input asp-for="EmployeeName" class="form-control" />
<span asp-validation-for="EmployeeName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EmployeeProfile" class="control-label"></label>
<div class="custom-file">
<input type="file" asp-for="EmployeeProfile" class="custom-file-input" />
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<span asp-validation-for="EmployeeProfile" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-sm btn-primary rounded-0" />
<a asp-action="Index" class="btn btn-sm btn-primary rounded-0">Back to List</a>
</div>
</form>
</div>
Model:
public class Employee
{
[Key]
public int Id { get; set; }
public string EmployeeName { get; set; }
public string EmployeeImage { get; set; }
}
public class EmployeeViewModel
{
public int Id { get; set; }
public string EmployeeName { get; set; }
public string LastName { get; set; }
[NotMapped]
public IFormFile EmployeeProfile { get; set; }
}
Result:

Bundle IdentityUser to ticket

This is a homework assignment. Where I have to make a website with MVC 2.2 and Make it possible to make a ticket with some basic info and link IdentityUser to the ticket.
The Class:
public class Ticket
{
public int ID { get; set; }
[Required]
public string Klant { get; set; }
[Required]
public string Applicatie { get; set; }
[Required]
public string Onderwerp { get; set; }
[Required]
public string Omschrijving { get; set; }
public DateTime Datum { get; set; }
public string Status { get; set; }
}
The Controller:
public class TicketsController : Controller
{
private readonly ApplicationDbContext _context;
UserManager<IdentityUser> _userManager;
public TicketsController(UserManager<IdentityUser> userManager)
{
_userManager = userManager;
}
public TicketsController(ApplicationDbContext context)
{
_context = context;
}
// GET: Tickets
public async Task<IActionResult> Index()
{
return View(await _context.Ticket.ToListAsync());
}
This is added to the controller at the moment.
UserManager<IdentityUser> _userManager;
public TicketsController(UserManager<IdentityUser> userManager)
{
_userManager = userManager;
}
So I was asking myself how to do this and I would really appreciate it if someone knows what to do and can explain it well.
Thanks in advance.
If you need more info just ask.
Here is a working scenario for creating one ticket with one IdentityUser.
Ticket
public class Ticket
{
public int ID { get; set; }
[Required]
public string Klant { get; set; }
[Required]
public string Applicatie { get; set; }
[Required]
public string Onderwerp { get; set; }
[Required]
public string Omschrijving { get; set; }
public DateTime Datum { get; set; }
public string Status { get; set; }
public string IdentityUserId { get; set; }
public virtual IdentityUser IdentityUser { get; set; }
}
ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Ticket> Tickets { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Ticket>().HasOne(t => t.IdentityUser).WithMany();
}
}
TicketsController
public class TicketsController : Controller
{
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityUser> _userManager;
public TicketsController(ApplicationDbContext context
, UserManager<IdentityUser> userManager)
{
_context = context;
_userManager = userManager;
}
// GET: Tickets
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.Tickets.Include(t => t.IdentityUser);
return View(await applicationDbContext.ToListAsync());
}
// GET: Tickets/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var ticket = await _context.Tickets
.Include(t => t.IdentityUser)
.FirstOrDefaultAsync(m => m.ID == id);
if (ticket == null)
{
return NotFound();
}
return View(ticket);
}
// GET: Tickets/Create
public IActionResult Create()
{
ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id");
return View();
}
// POST: Tickets/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,Klant,Applicatie,Onderwerp,Omschrijving,Datum,Status,IdentityUserId")] Ticket ticket)
{
if (ModelState.IsValid)
{
_context.Add(ticket);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", ticket.IdentityUserId);
return View(ticket);
}
// GET: Tickets/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var ticket = await _context.Tickets.FindAsync(id);
if (ticket == null)
{
return NotFound();
}
ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", ticket.IdentityUserId);
return View(ticket);
}
// POST: Tickets/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Klant,Applicatie,Onderwerp,Omschrijving,Datum,Status,IdentityUserId")] Ticket ticket)
{
if (id != ticket.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(ticket);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TicketExists(ticket.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", ticket.IdentityUserId);
return View(ticket);
}
// GET: Tickets/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var ticket = await _context.Tickets
.Include(t => t.IdentityUser)
.FirstOrDefaultAsync(m => m.ID == id);
if (ticket == null)
{
return NotFound();
}
return View(ticket);
}
// POST: Tickets/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var ticket = await _context.Tickets.FindAsync(id);
_context.Tickets.Remove(ticket);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool TicketExists(int id)
{
return _context.Tickets.Any(e => e.ID == id);
}
}
Create.cshtml
#model CoreIdentity2.Models.Ticket
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Ticket</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Klant" class="control-label"></label>
<input asp-for="Klant" class="form-control" />
<span asp-validation-for="Klant" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Applicatie" class="control-label"></label>
<input asp-for="Applicatie" class="form-control" />
<span asp-validation-for="Applicatie" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Onderwerp" class="control-label"></label>
<input asp-for="Onderwerp" class="form-control" />
<span asp-validation-for="Onderwerp" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Omschrijving" class="control-label"></label>
<input asp-for="Omschrijving" class="form-control" />
<span asp-validation-for="Omschrijving" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Datum" class="control-label"></label>
<input asp-for="Datum" class="form-control" />
<span asp-validation-for="Datum" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Status" class="control-label"></label>
<input asp-for="Status" class="form-control" />
<span asp-validation-for="Status" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="IdentityUserId" class="control-label"></label>
<select asp-for="IdentityUserId" class ="form-control" asp-items="ViewBag.IdentityUserId"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Categories

Resources