I'm doing an mvc Theater project with entity framework code first.
I created a page to add a movie to my database.
the Movie class has a Genre property,the Genre class has an Id and a Name property.
What I'm trying to do is query all rows of the Genres table from database with Linq (if other method is better do tell) and choose one Genre to connect to a row of the movie I'm creating.
thanks,any help is appreciated.
this is my Genre class
public class Genre
{
[Key]
public int Id { get; set; }
[Display(Name="Ganre")]
public string GenreName { get; set; }
public virtual ICollection<Movie> MoviesByGenre { get; set; }
}
this is my Movie class
public class Movie
{
[Key]
public string Id { get; set; }
[Required(ErrorMessage = "Movie name is required")]
[Display(Name="Movie name")]
public string MovieName { get; set; }
[Required(ErrorMessage = "Movie length is required")]
[Display(Name="Length(minutes)")]
public int LengthInMinutes { get; set; }
[Required(ErrorMessage="Genre of the movie is required")]
[Display(Name="Genre")]
public virtual Genre MovieGenre { get; set; }
public string Description { get; set; }
[Required(ErrorMessage = "Year of release is required")]
public int Year { get; set; }
[Required(ErrorMessage="Who is the director?")]
public virtual MovieDirector Director { get; set; }
public virtual MoviePoster Poster { get; set; }
//How many users bought a ticket
public virtual ICollection<ApplicationUser> UsersWhoBoughtTicket { get; set; }
}
this is the Add Movie page
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.MovieName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MovieName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MovieName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LengthInMinutes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LengthInMinutes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LengthInMinutes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Year, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Year, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Year, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MovieGenre.GenreName, htmlAttributes: new { #class = "btn control-label col-md-2" })
<div class="col-md-10">
#Html.ValidationMessageFor(model => model.MovieGenre.GenreName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Director, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Director, new { htmlAttributes = new { #class = "form-control dropdown" } })
#Html.ValidationMessageFor(model => model.Director, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Poster, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="Image" type="file" />
#Html.ValidationMessageFor(model => model.Poster)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
I hope your entities are like this:
public class Genre
{
public int Id{ get; set; }
public string Name{ get; set; }
public ICollection<Movie> Movies{ get; set; }
}
public class Movie
{
public int Id{ get; set; }
public string Name{ get; set; }
public int GenreId {get; set; }
public Genre Genre{ get; set; }
}
Now your query would be like this:
_context.Include(x=>x.Movies).Genres; //it will return all genres with movies
_context.Movies.where(x=>x.GenreId == genreId); // it will return movies based on a genre id
Related
I have created a Form that takes input from the user and saves it to tblFuelTroubleTickets, I am populating some fields from other tables as a dropdown list for instance tblsites stores all the Sites details along with ClusterOwners, both tables are joined.
enter image description here
Attached is the Form i am taking some parameters from users but i dont want to take ClusterOwnerName from user as tblsites stores all Site details, so when user select the SiteID the progame must takes the detais from tblsites and saved it into tblFuelTroubleTickets along with other input details.
This is the View
#model MyTempWorking.Models.TTCreateModel
#{
Layout = null;
if (Session["userID"] == null)
{
Response.Redirect("~/Login/Index");
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CreateTT</title>
</head>
<body>
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>TTCreateModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("Site ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("SiteCode", ViewBag.sitec as SelectList, "Select Site", new { htmlAttributes = new { #class = "form-control" } })
#*#Html.DropDownListFor(model => model.SiteCode, ViewBag.sitec as SelectList, "Select Site", new { htmlAttributes = new { #class = "form-control" } })*#
#*#Html.EditorFor(model => model.SiteCode, new { htmlAttributes = new { #class = "form-control" } })*#
#*#Html.ValidationMessageFor(model => model.SiteCode, "", new { #class = "text-danger" })*#
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RegionCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RegionCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RegionCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Area", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AreaCode, new { htmlAttributes = new { #class = "form-control" } })
#*#Html.EditorFor(model => model.AreaCode, new { htmlAttributes = new { #class = "form-control" } })*#
#*#Html.ValidationMessageFor(model => model.AreaCode, "", new { #class = "text-danger" })*#
</div>
</div>
<div class="form-group">
#Html.Label("Visit Type", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.VisitCode, ViewBag.sitevc as SelectList, "Select Visit Type", new { htmlAttributes = new { #class = "form-control" } })
#*#Html.EditorFor(model => model.VisitCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.VisitCode, "", new { #class = "text-danger" })*#
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RequiredFuelFilled, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RequiredFuelFilled, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RequiredFuelFilled, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RequiredVisitDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RequiredVisitDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RequiredVisitDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Cluster Owner Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ClusterOwnerCode, ViewBag.Cuslname as SelectList, "Select Cluster Owner", new { htmlAttributes = new { #class = "form-control" } })
#*#Html.ValidationMessageFor(model => model.ClusterOwnerCode, "", new { #class = "text-danger" })*#
</div>
</div>
<div class="form-group">
#Html.Label("CP Status", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CPStatusCode, ViewBag.Cpname as SelectList, "Select CP Status", new { htmlAttributes = new { #class = "form-control" } })
#*#Html.ValidationMessageFor(model => model.CPStatusCode, "", new { #class = "text-danger" })*#
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
This is the Controller
[HttpGet]
public ActionResult CreateTT()
{
List<tblClusterOwner> list = db.tblClusterOwners.ToList();
ViewBag.Cuslname = new SelectList(list, "ClusterOwnerCode", "ClusterOwnerName");
List<tblSiteCPStatu> list2 = db.tblSiteCPStatus.ToList();
ViewBag.Cpname = new SelectList(list2, "CPStatusCode", "CPStatus");
List<tblSite> list3 = db.tblSites.Where(x => x.Active==true).ToList();
ViewBag.sitec = new SelectList(list3, "SiteCode", "SiteID");
List<tblSiteVisitType> list4 = db.tblSiteVisitTypes.ToList();
ViewBag.sitevc = new SelectList(list4, "VisitCode", "VisitName");
return View();
}
[HttpPost]
public ActionResult CreateTT(tblFuelTroubleTicket fctt)
{
db.tblFuelTroubleTickets.Add(fctt);
fctt.CreatedDate = DateTime.Now;
fctt.CreatedBy = User.Identity.Name;
fctt.IsActive = true;
//fctt.AreaCode=
db.SaveChanges();
return RedirectToAction("DisplayTTs");
}
My Model Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyTempWorking.Models
{
public class TTCreateModel
{
public long TT { get; set; }
public int SiteCode { get; set; }
public long RegionCode { get; set; }
public Nullable<long> AreaCode { get; set; }
public string VisitCode { get; set; }
[System.ComponentModel.DataAnnotations.DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<System.DateTime> RequiredVisitDate { get; set; }
public Nullable<decimal> RequiredFuelFilled { get; set; }
public string CPStatusCode { get; set; }
public string SiteStatusCode { get; set; }
public string InitiatorRemarks { get; set; }
public Nullable<int> ClusterOwnerCode { get; set; }
public Nullable<long> VendorCode { get; set; }
public Nullable<bool> IsActive { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public string SiteID { get; set; }
public string VisitName { get; set; }
public string AreaName { get; set; }
public string ClusterOwnerName { get; set; }
public string CPStatus { get; set; }
}
}
I must not be searching with the correct phrases. This is a simple concept and I’ve done it in other languages and frameworks with ease.
I’m saving the UserID for the person who created the record and the UserID who last updated the record. Instead of displaying the UserID, I want to display the User.FirstName + ‘ ‘ + User.LastName.
The way I have it currently the LastEditBy and CreateBy is displayed on the page as blank.
Controller: I get the customer model and manually map the model to the customerViewModel then pass it to my partial view.
public ActionResult Edit(int customerId)
{
Customer customer = DbContext.Customers.FirstOrDefault(x => x.CustomerId == customerId);
CustomerViewModel customerViewModel = MapToViewModel(customer);
customerViewModel.UserSelectList = GetUserGroupList();
UserManager<ApplicationUser> _userManager = HttpContext.GetOwinContext().Get<ApplicationUserManager>();
var CreateByUser = _userManager.FindById(customerViewModel.CreateById);
var EditByUser = _userManager.FindById(customerViewModel.LastEditById);
customerViewModel.CreateBy = CreateByUser.FirstName + " " + CreateByUser.LastName;
customerViewModel.LastEditBy = EditByUser.FirstName + " " + EditByUser.LastName;
if (Request.IsAjaxRequest()) {
return PartialView("_CustomerEditPartial", customerViewModel);
}
return View("_CustomerEditPartial", customerViewModel);
}
The CustomerViewModel:
public class CustomerViewModel : DbContext{
public CustomerViewModel(): base("name=CustomerViewModel")
{
}
[Key]
public int CustomerId { get; set; }
[MaxLength(128), ForeignKey("ApplicationUser")]
public string UserId { get; set; }
public SelectList UserSelectList { get; set; }
#region additional Fields
// This overrides default conventions or data annotations
[Required(ErrorMessage = "Please enter your first name.")]
[StringLength(50)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter your last name.")]
[StringLength(100)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime CreateDate { get; set; } = DateTime.Now;
public string CreateById { get; set; }
[NotMapped]
public string CreateBy { get; set; }
public string LastEditById { get; set; }
[NotMapped]
public string LastEditBy { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime LastEditDate { get; set; } = DateTime.Now;
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class UserGroupList
{
public string Value { get; set; }
public string Text { get; set; }
}
My partial view page: _CustomerEditPartial.cshtml
#model WOA.ViewModels.CustomerViewModel
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" daa-dismiss="modal" aria-hidden="True">x</button>
<h4 class="modal-title">Edit Customer</h4>
</div>
#using (Ajax.BeginForm("Edit", "Customers", null, new AjaxOptions { HttpMethod = "Post", OnFailure = "OnFail" }, new { #class = "form-horizontal", role = "form" })) {
<div class="modal-body">
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.CustomerId)
<div class="form-group">
#Html.LabelFor(model => model.UserId, "UserId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.UserId, ViewData.Model.UserSelectList, "Select One", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreateDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CreateDate, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreateBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CreateBy, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastEditBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.LastEditBy, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastEditDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.LastEditDate, new { #readonly = "readonly" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Save changes" />
</div>
</div>
</div>
<script type="text/javascript">
function OnSuccess() {
alert("success");
}
function OnFail() {
alert("fail");
}
function OnComplete() {
alert("Complete");
}
</script>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I have updated my code, it is working now, however I do not believe it is the proper way to do this.
I believe I should be able to return the additional values I need via Linq on the initial call and not make two more trips to the database for the additional values.
I have not been able to figure out a way to make this work with Linq.
Thank you in advance for your time and effort.
As you can see in the code, I have two classes in RegistratieViewModel. When I pass my viewmodel to my view it only recognizes the class Selectie and not Reizigers? Can someone help me out?
I get the error: 'CS1061 C# does not contain a definition for and no extension method accepting a first argument of type could be found (are you missing a using directive or an assembly reference?)'
Viewmodel
public class RegistratieViewModel
{
public SelectieViewModel Selectie { get; set; }
public List<ReizigersViewModel> Reizigers { get; set; }
public RegistratieViewModel()
{
Reizigers = new List<ReizigersViewModel>();
}
}
public class SelectieViewModel
{
public SelectList VanStad { get; set; }
public SelectList NaarStad { get; set; }
public bool Klasse { get; set; }
public DateTime DatumHeenReis { get; set; }
public DateTime DatumTerugReis { get; set; }
public int AantalReizigers { get; set; }
}
public class ReizigersViewModel
{
public string Voornaam { get; set; }
public string Familienaam { get; set; }
}
Controller
// GET: Hotels/Index
public ActionResult Index(RegistratieViewModel registratie)
{
stedenServices = new StedenServices();
RegistratieViewModel registratieviewmodel = new RegistratieViewModel();
registratieviewmodel.Selectie.VanStad = new SelectList(stedenServices.All(), "StadID", "Stad");
registratieviewmodel.Selectie.NaarStad = new SelectList(stedenServices.All(), "StadID", "Stad");
return View(registratieviewmodel);
}
View
#model Treinreizen.Models.ViewModels.RegistratieViewModel
<div class="form-horizontal">
<h4>RegistratieViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Reizigers.Voornaam, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Reizigers.Voornaam, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Reizigers.Voornaam, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Reizigers.Familienaam, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Reizigers.Familienaam, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Reizigers.Familienaam, "", new { #class = "text-danger" })
</div>
</div>
</div>
The problem is that you're referencing a property on ReizigersViewModel on a List<ReizigersViewModel>. The list doesn't have that property, only a single item of that list will. You can't create a single set of fields for an entire collection. You must iterate over the collection:
#for (var i = 0; i < Model.Reizigers.Count(); i++)
{
<div class="form-group">
#Html.LabelFor(model => model.Reizigers[i].Voornaam, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Reizigers[i].Voornaam, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Reizigers[i].Voornaam, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Reizigers[i].Familienaam, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Reizigers[i].Familienaam, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Reizigers[i].Familienaam, "", new { #class = "text-danger" })
</div>
</div>
}
Note the use of the indexing syntax in the HtmlHelper expressions. Now, you're referencing a single item in the List<ReizigersViewModel>, i.e. ReizigersViewModel, instead of the whole list.
Following are my two connected models.
When I post data with single Invoice and multiple Invoice_Details entry,
I found Invoice_Details blank inside Invoice object.
I am using EditorTemplate as you can see in below code.
How can I save single Invoice and Multiple Invoice_Details entry.
Invoice
public class Invoice
{
[UIHint("Invoice_Details")]
public virtual List<Invoice_Details> Invoice_Details { get; set; }
public Invoice()
{
Invoice_Details = new List<Models.Invoice_Details>();
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Display(Name = "Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DATE { get; set; }
[Key]
[Display(Name = "Invoice no")]
[Required]
public int INVOICENO { get; set; }
[Display(Name = "Party")]
public int PARTY { get; set; }
[Display(Name = "Broker")]
public int BROKER { get; set; }
[Display(Name = "Terms")]
[Required]
public int TERMS { get; set; }
[Display(Name = "Brokerage")]
[Required]
public decimal BROKERAGE { get; set; }
[Display(Name = "Article")]
[Required]
public string ARTICLE { get; set; }
[Display(Name = "Total")]
public decimal TOTAL { get; set; }
[Display(Name = "Details")]
public string DETAILS { get; set; }
[ScaffoldColumn(false)]
public DateTime CREATE_TIMESTAMP { get; set; }
[ScaffoldColumn(false)]
public DateTime LAST_EDIT_TIMESTAMP { get; set; }
}
Invoice_Details
public class Invoice_Details
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Display(Name = "Invoice no")]
[Required]
public int INVOICENO { get; set; }
[Display(Name = "Caret")]
public decimal CARET { get; set; }
[Display(Name = "Price")]
public decimal PRICE { get; set; }
[Display(Name = "Rs/Dollar")]
[Required]
public string RUPEESDOLLAR { get; set; }
[Display(Name = "Rate")]
[Required]
public decimal RATEIFDOLLAR { get; set; }
[Display(Name = "Total")]
public decimal TOTAL { get; set; }
[ScaffoldColumn(false)]
public DateTime CREATE_TIMESTAMP { get; set; }
[ScaffoldColumn(false)]
public DateTime LAST_EDIT_TIMESTAMP { get; set; }
public virtual Invoice invoice { get; set; }
}
CREATE VIEW
#model SKUMAR.Models.Invoice
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Invoice</h4>
<hr />
<div class="col-md-6">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.INVOICENO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.INVOICENO, new { htmlAttributes = new {#autofocus="autofocus", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.INVOICENO, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DATE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.DATE,new {#Value=ViewBag.CURRENTDATE, #class = "form-control" } )
#Html.ValidationMessageFor(model => model.DATE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PARTY, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PARTY, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PARTY, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BROKER, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BROKER, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BROKER, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TERMS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TERMS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TERMS, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BROKERAGE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BROKERAGE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BROKERAGE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ARTICLE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ARTICLE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ARTICLE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TOTAL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TOTAL, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TOTAL, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DETAILS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DETAILS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DETAILS, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6">
#Html.EditorFor(m=>m.Invoice_Details)
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Invoice_Details.cshtml EditorTemplate
#model SKUMAR.Models.Invoice_Details
<table class="table table-bordered table-hover">
<tr>
<td>#Html.TextBoxFor(m=>m.CARET, new { #class = "form-control" })</td>
<td>#Html.TextBoxFor(m => m.PRICE, new { #class = "form-control" })</td>
<td>#Html.TextBoxFor(m => m.RUPEESDOLLAR, new { #class = "form-control" })</td>
<td>#Html.TextBoxFor(m => m.RATEIFDOLLAR, new { #class = "form-control" })</td>
<td>#Html.TextBoxFor(m => m.TOTAL, new { #class = "form-control" })</td>
</tr>
</table>
Inside Invoice_Details.cshtml EditorTemplate instead of #model SKUMAR.Models.Invoice_Details , use #model SKUMAR.Models.Invoice and then change every line based on that. For example change #Html.TextBoxFor(m=>m.CARET to #Html.TextBoxFor(m=>m.Invoice_Details.CARET.
I have base class Contract
public abstract class Contract
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ContractID { get; set; }
[DataType(DataType.Date)]
[Required]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
[Required]
public DateTime EndDate { get; set; }
}
And two other classes derive from this class: CreditContract and PrepaymentContract.
public class CreditContract : Contract
{
[Required]
public float CreditLimit { get; set; }
[Column(TypeName = "char")]
[StringLength(3)]
[Required]
public string CreditLimitCurrency { get; set; }
}
public class PrepaymentContract : Contract
{
[Required]
public float PrepaymentAmount { get; set; }
[Column(TypeName = "char")]
[StringLength(1)]
[Required]
public string PrepaymentPeriod { get; set; }
}
Additionally I've created ContractViewModel class.
public int SelectedContract { get; set; }
public CreditContract creditContract { get; set; }
public PrepaymentContract prepaymentContract { get; set; }
My Create method looks like this:
public ActionResult Create(ContractViewModel contract)
{
if (contract.SelectedCategory == 1)
{
if (ModelState.IsValid)
{
contract.creditContract.StartDate = contract.StartDate;
contract.creditContract.EndDate = contract.EndDate;
db.Contracts.Add(contract.creditContract);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contract.creditContract);
}
else
{
if (ModelState.IsValid)
{
contract.prepaymentContract.StartDate = contract.StartDate;
contract.prepaymentContract.EndDate = contract.EndDate;
db.Contracts.Add(contract.prepaymentContract);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contract.prepaymentContract);
}
}
And my Create view looks like this:
#model CodeFirstInheritance.ViewModels.ContractViewModel
<div class="form-horizontal">
<h4>Course</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.creditContract.StartDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.creditContract.StartDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.creditContract.StartDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.creditContract.EndDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.creditContract.EndDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.creditContract.EndDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SelectedCategory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SelectedCategory, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SelectedCategory, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.creditContract.CreditLimit, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.creditContract.CreditLimit, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.creditContract.CreditLimit, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.creditContract.CreditLimitCurrency, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.creditContract.CreditLimitCurrency, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.creditContract.CreditLimitCurrency, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
Can I do something like that:
E.g:
var selectedContract = contract.SelectedCategory.Enum;
if (ModelState.IsValid)
{
selectedContractt.StartDate = contract.StartDate;
selectedContract.EndDate = contract.EndDate;
db.Contracts.Add(contract.creditContract);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(selectedContract);