How to create a drop-down in asp.net core MVC from another Model with validation? - asp.net

Model Class.cs
public class Class
{
public int ClassId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
[Required]
[Display(Name = "Class Name")]
public string ClassName { get; set; }
}
Model Subject.cs
public class Subject
{
public int SubjectId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
public string SubjectName { get; set; }
public int ClassId { get; set; }
public Class Class { get; set; }
}
ViewModel CreateSubjectViewModel.cs
public class CreateSubjectViewModel
{
public int SubjectId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
[Required]
[Display(Name = "Subject Name")]
public string SubjectName { get; set; }
public int ClassId { get; set; }
public int ClassesId { get; set; }
public virtual List<Class> Classes { get; set; }
}
Controller Code
[HttpGet]
public IActionResult CreateSubject()
{
List<Class> classList = _context.Classes.ToList();
ViewData["classList"] = classList.Select(x => new SelectListItem { Value = x.EncryptedId, Text = x.ClassName });
return View();
}
[HttpPost]
public IActionResult CreateSubject(CreateSubjectViewModel model)
{
if (ModelState.IsValid)
{
Subject newSubject = new Subject
{
//SubjectName = model.SubjectName,
//here code for store data in subject table
};
_cdsRepository.AddSubject(newSubject);
return RedirectToAction("ListClasses", "UDP");
}
return View(model);
}
How can I get data from Class.cs and show in drop-down with proper validation of drop-down on button click.
If everything is OK, then store data in Subject.cs with Class Id value.

Related

Can't convert from model to viewmodel, using AutoMapper asp.net core

I am using Auto mapper to map between modelviews and models. I have followed the same steps given by the Auto mapper documentation and still can't find where the issue is.
public class RegisterStaffViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "StaffName Required")]
public string StaffName { get; set; }
[Required(ErrorMessage = "Gender Required")]
public string Gender { get; set; }
[Required(ErrorMessage = "Address Required")]
public string Address { get; set; }
[Required(ErrorMessage = "StaffCode Required")]
public string StaffCode { get; set; }
[DisplayName("Department")]
[Required(ErrorMessage = "Department is Required")]
public int? DepartmentId { get; set; }
public string CardNo { get; set; }
[Required(ErrorMessage = "Mobileno Required")]
[RegularExpression(#"^(\d{10})$", ErrorMessage = "Wrong Mobileno")]
public string MobileNo { get; set; }
[Required(ErrorMessage = "EmailID Required")]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]
public string Email { get; set; }
public DateTime EntryDate { get; set; }
[Display(Name = "Position")]
[Required(ErrorMessage = "Position is Required")]
public int? PositionId { get; set; }
[Display(Name = "Staff Type")]
[Required(ErrorMessage = "Staff Type is Required")]
public int? StaffTypeId { get; set; }
public string CardIdNo { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsUpdated { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
public string DeletedBy { get; set; }
public string Remarks { get; set; }
public virtual ApplicationUser CreatedByNavigation { get; set; }
public virtual ApplicationUser DeletedByNavigation { get; set; }
public virtual Departments Department { get; set; }
public virtual Positions Position { get; set; }
public virtual StaffTypes StaffType { get; set; }
public virtual ApplicationUser UpdatedByNavigation { get; set; }
public virtual ICollection<AttendanceRecorderViewModel> AttendanceRecorder { get; set; }
public virtual ICollection<ManageLeavesViewModel> ManageLeaves { get; set; }
public virtual ICollection<RegisterDevicesViewModel> RegisterDevices { get; set; }
}
=============================================================================================
public partial class RegisterStaffs
{
public int Id { get; set; }
public string StaffName { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string StaffCode { get; set; }
public int? DepartmentId { get; set; }
public string CardNo { get; set; }
public string MobileNo { get; set; }
public string Email { get; set; }
public DateTime EntryDate { get; set; }
public int? PositionId { get; set; }
public int? StaffTypeId { get; set; }
public string CardIdNo { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsUpdated { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
public string DeletedBy { get; set; }
public string Remarks { get; set; }
public virtual ApplicationUser CreatedByNavigation { get; set; }
public virtual ApplicationUser DeletedByNavigation { get; set; }
public virtual Departments Department { get; set; }
public virtual Positions Position { get; set; }
public virtual StaffTypes StaffType { get; set; }
public virtual ApplicationUser UpdatedByNavigation { get; set; }
public virtual ICollection<AttendanceRecorder> AttendanceRecorder { get; set; }
public virtual ICollection<ManageLeaves> ManageLeaves { get; set; }
public virtual ICollection<RegisterDevices> RegisterDevices { get; set; }
}
============================================================================================
public interface IMapperConfig
{
IMapper CreateMapper();
}
public class MapperConfig : IMapperConfig
{
public IMapper CreateMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RegisterStaffs, RegisterStaffViewModel>();
cfg.CreateMap<AttendanceRecorder, AttendanceRecorderViewModel>();
cfg.CreateMap<ManageLeaves, ManageLeavesViewModel>();
cfg.CreateMap<RegisterDevices, RegisterDevicesViewModel>();
});
return config.CreateMapper();
}
}
==========================================================================================
public async Task<ReturnResult<List<RegisterStaffViewModel>>> GetAllEmployees()
{
var result = new ReturnResult<List<RegisterStaff>>();
try
{
var employees = await context.RegisterStaffs.Where(x => (bool)!x.IsDeleted).OrderByDescending(x => x.EntryDate).AsNoTracking().ToListAsync();
// **here is the error**
result.Success(mapper.Map<List<RegisterStaffs>, List<RegisterStaffViewModel>>(employees));
}
catch(Exception ex)
{
}
return result;
}
============================================================================================
public class ReturnResult<T>
{
public ReturnResult()
{
ErrorList = new List<string>();
}
public bool IsSuccess { get; set; }
public HttpCode HttpCode { get; set; }
public T Data { get; set; }
public List<string> ErrorList { get; set; }
/// <summary>
/// Set success result with data
/// </summary>
/// <param name="Data"></param>
public void Success(T Data)
{
this.IsSuccess = true;
this.HttpCode = HttpCode.Success;
this.Data = Data;
}
/// <summary>
/// Set Server Error result with error message
/// </summary>
/// <param name="Error"></param>
public void ServerError(string Error)
{
this.IsSuccess = false;
this.HttpCode = HttpCode.ServerError;
this.ErrorList.Add(Error);
}
/// <summary>
/// Set Not Found result with error message
/// </summary>
/// <param name="Error"></param>
public void NotFound(string Error)
{
this.IsSuccess = false;
this.HttpCode = HttpCode.NotFound;
this.ErrorList.Add(Error);
}
}
I found the issue was here
var result = new ReturnResult<List<RegisterStaff>>();
i have changed it to
var result = new ReturnResult<List<RegisterStaffViewModel>>();

generate a list of products of a category

I am developing a shop application and I need to show products of each category. The problem is each product is created from a product template which is stored in a table and each template is related to a category. here is the product model:
namespace fardashahr.Models
{
[Table("Product")]
public class ProductModel
{
public ProductModel()
{
if (Specs == null)
{
Specs = new Dictionary<string, SpecItemsModel>();
}
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public int ProductTemplateId { get; set; }
[Required]
public bool IsPublished { get; set; }
[Required]
public bool InStock { get; set; }
[Range(95, 110)]
public float SyncRate { get; set; }
public DateTime? ProductionDate { get; set; }
[Required]
public DateTime RegisterationDate { get; set; }
public string ImageName { get; set; }
public IEnumerable<string> GalleryImages { get; set; }
[NotMapped]
public Dictionary<string, SpecItemsModel> Specs { get; set; }
[ForeignKey("ProductTemplateId")]
public virtual ProductTemplateModel ProductTemplate { get; set; }
[ForeignKey("ManufacturerId")]
public virtual CodingItemModel Manufacturer { get; set; }
[ForeignKey("BrandId")]
public virtual CodingItemModel Brand { get; set; }
[ForeignKey("ModelId")]
public virtual CodingItemModel Model { get; set; }
[ForeignKey("SeriesId")]
public virtual CodingItemModel Series { get; set; }
}
}
and here is the the ProductTemplate:
namespace fardashahr.Models
{
[Table("ProductTemplate")]
public class ProductTemplateModel
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[StringLength(500)]
public string Name { get; set; }
[Required]
public int CategoryId { get; set; }
[StringLength(500)]
public string Description { get; set; }
[ForeignKey("CategoryId")]
public virtual CategoryModel Category{ get; set; }
}
}
and the controller is:
namespace fardashahr.Controllers
{
public class ProductsController : Controller
{
// GET: Products
public ActionResult Index()
{
return RedirectToAction("Index", "Home");
}
public ActionResult Category(string name)
{
//declare a list of products
List<ProductModel> productList;
using(MainModel db = new MainModel())
{
//get category id
CategoryModel category = db.Categories.Where(x => x.CategorytUrl == name).FirstOrDefault();
int catId = category.Id;
//initialize the list
productList = db.Products.Where(x => x. == catId).ToList();
}
}
}
}
finaly, what I want to know is how to initialize a list of products.
In your models, you added virtual keyword which indicates that navigation property will be automatically loaded without the need of LINQ lambda .include() expression.
Hence you can immediately access the navigation property and load the list like this;
productList = db.Products.Where(x => x.ProductTemplate.CategoryId == catId).ToList();
string categoryNameOfFirstProduct = productList.FirstOrDefault().ProductTemplate.Category.Name;
string categoryNameOfFirstProduct = productList.FirstOrDefault().ProductTemplate.Category.CategorytUrl;

Trying to recreate a solution given for a question, need a little assistance

Trying to recreate a solution given for ASP.NET MVC - Taking search criteria as input, and displaying the results, in the same View?, but not sure where to find the querymanager that derloopkat uses in his example.
[HttpPost]
public ActionResult Query(FormQueryModel model)
{
var queryManager = new QueryManager(model);
model.QueryResults = queryManager.GetResults();
return View(model);
}
My ViewModels
public class PartRequestInfoSearch
{
public int? Building { get; set; }
public int? PartType { get; set; }
public int? PartStatus { get; set; }
public Nullable<System.DateTime> tmpStartDate { get; set; }
public Nullable<System.DateTime> tmpEndDate { get; set; }
public int PageSize { get; set; }
public List<RequestedPartInfo> RequestedPartInfos { get; set; }
public PartRequestInfoSearch()
{
this.RequestedPartInfos = new List<RequestedPartInfo>();
}
}
}
public class RequestedPartInfo
{
public int idPartRequest { get; set; }
public string Building { get; set; }
public string RequestNumber { get; set; }
public string PartNumber { get; set; }
public string VendorPartNumber { get; set; }
public string PartDescription { get; set; }
public int StockQTY { get; set; }
public int RequestQTY { get; set; }
public int ShippedQTY { get; set; }
public string PartStatus { get; set; }
}

MVC 5 Complex View Model binding is not working

public class CreateProjeModel
{
public Proje Proje { get; set; }
public List<GeometryModel> GeometryList { get; set; }
public CreateProjeModel()
{
Proje = new Proje();
GeometryList = new List<GeometryModel>();
}
}
public class GeometryModel
{
public List<PointModel> PointList { get; set; }
public GeometryModel()
{
PointList = new List<PointModel>();
}
}
public class PointModel
{
public int X { get; set; }
public int Y { get; set; }
}
public class Proje : EntityBase
{
public int FirmaId { get; set; }
public int IlId { get; set; }
public int? IlceId { get; set; }
public int PlanTurId { get; set; }
public int EtudTurId { get; set; }
public int EtudAmacId { get; set; }
public int DilimId { get; set; }
public string Aciklama { get; set; }
public virtual Firma Firma { get; set; }
public virtual IL Il { get; set; }
public virtual ILCE Ilce { get; set; }
public virtual PlanTur PlanTur { get; set; }
public virtual EtudTur EtudTur { get; set; }
public virtual EtudAmac EtudAmac { get; set; }
public virtual Dilim Dilim { get; set; }
}
I have a complex model named CreateProjeModel. I'm using 'for' to loop collection properties and binding like below:
#Html.TextBoxFor(m => m.GeometryList[i].PointList[j].X)
Action is like below:
[HttpPost]
public async Task<ActionResult> Create(CreateProjeModel proje)
{
//ToDo
return View(proje);
}
Posted data is below:
When it comes to action, GeometryList is empty and Proje's properties are not set to post values. Where am I doing wrong?
Your problem is that your CreateProjeModel model has a property named Proje, but the parameter of your Create() method is also named proje. Your need to change the method signature to (say)
public async Task<ActionResult> Create(CreateProjeModel model)
where the parameter name is not the same as the nae of one of your properties

How to make single view using viewmodel in asp.net mvc 4?

I have different models Image,Page & PageCategories
public class Image
{
public int ImageId { get; set; }
public string ImageTitle { get; set; }
public string ImageURL { get; set; }
}
public class Page
{
public int PageId { get; set; }
public string PageTitle { get; set; }
public string Content { get; set; }
public int PageCategoryId { get; set; }
public virtual PageCategory PageCategory { get; set; }
}
public class PageCategory
{
public int PageCategoryId { get; set; }
public string CategoryName { get; set;
public virtual ICollection<Page> Pages { get; set; }
}
DBContext Class is
class DemoContext:DbContext
{
public DbSet<PageCategory> PageCategories { get; set; }
public DbSet<Page> Pages { get; set; }
public DbSet<Image> Images { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
I am wondering how to get all the model data to the home page using ViewModel.
For Ex.:
How to get image list and Page list in home page from multiple models?
You may want something like this :
viewModel :
//Create a viewModel with all the properties that you need
public class ViewModel
{
public int ImageId { get; set; }
public string ImageTitle { get; set; }
public string ImageURL { get; set; }
public int PageId { get; set; }
public string PageTitle { get; set; }
public string Content { get; set; }
public int PageCategoryId { get; set; }
public string CategoryName { get; set; }
}
Controller :
...
using (DemoContext db = new DemoContext()){
List<ImagePageViewModel> viewData = (from p in db.Page
join pc from db.PageCategory on p.PageCategoryId equals pc.PageCategoryId
select new ViewModel(){
PageTitle=p.PageTitle,
CategoryName = pc.CategoryName
//... set every property you want
})
}
return View(viewData );
note: I didn't add Image to the query because there is no explicit relation
between Image and the others table so i let you do it.
Create another class and define all above three into it. like below
public class MyView
{
public List<Image> Images { get; set; }
public List<Page> Pages { get; set; }
public List<PageCategory> PageCategories { get; set; }
}
Controller Action:-
public ActionResult Index()
{
MyView myView = // Get it using your logic
return View(myView);
}
finally got my answer:
public class ViewModelDemo
{
public IEnumerable<Image> images { get; set; }
public IEnumerable<Pages> pages { get; set; }
public IEnumerable<PageCategory> pagecategories { get; set; }
}
Then in HomeController
private DemoContext db=new DemoContext();
public ActionResult Index()
{
ViewModelDemo vm = new ViewModelDemo();
vm.images = db.Images.ToList();
vm.pages=db.Pagess.ToList();
vm.pagecategories=db.PageCategories.ToList();
return View(vm);
}

Resources