How create single create action for multiple models with TPH approach - asp.net-mvc

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);

Related

Asp.net MVC Saving Data from other tables to the Source Table

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; }
}
}

POST form in MVC - No Values being written to DB

I have a model that I'm trying to edit with a form:
public class Basiclife
{
[Key]
public int Id { get; set; }
public int? ResponseId { get; set; }
public string Plantype { get; set; }
public int Enrolledftes { get; set; }
public decimal Pctemployer { get; set; }
public decimal Fixedbenamt { get; set; }
public decimal Salarymult { get; set; }
public decimal Bencap { get; set; }
}
And a view wrapper to edit it (with the editor in a separate partial view):
<h2>CreateBasicLifeResponse</h2>
<div id="planList">
#using (Html.BeginForm("CreateBasicLifeResponse", "Surveys"))
{
<div id="editorRows">
#foreach (var item in Model.basiclives)
{
#Html.Partial("_BasicLifeResponse", item)
}
</div>
#Html.ActionLink("Add", "BasicLifeResponse", null, new { id = "addItem", #class = "button" });
<input type="submit" value="submit" />
}
</div>
The wrapper's model is:
public class ResponseBasicLife
{
public Response response { get; set; }
public List<Basiclife> basiclives { get; set; }
}
Here's the partial view:
#using CustomSurveyTool.Models
#model Basiclife
<div class="editorRow">
#using (Html.BeginCollectionItem("basiclives"))
{
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Plantype, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Plantype, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Plantype, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Enrolledftes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Enrolledftes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Enrolledftes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Pctemployer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Pctemployer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Pctemployer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Fixedbenamt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Fixedbenamt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Fixedbenamt, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Salarymult, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Salarymult, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Salarymult, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Bencap, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Bencap, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Bencap, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
X
</div>
</div>
}
</div>
Here's my controller action where I'm getting the proper responseId and assigning it to the form values:
public ActionResult CreateBasicLifeResponse(ResponseBasicLife model)
{
for (var i = 1; i < model.basiclives.Count; i++)
{
string currentUserId = User.Identity.GetUserId();
Response targetresponse = db.response.FirstOrDefault(x => x.Userid == currentUserId);
int responseid = targetresponse.Id;
model.basiclives[i].ResponseId = responseid;
db.basiclife.Add(model.basiclives[i]);
db.SaveChanges();
}
ResponseBasicLife basicliferesponse = new ResponseBasicLife
{
basiclives = new List<Basiclife>
{
new Basiclife { }
}
};
return View(basicliferesponse);
}
The only thing that's being written to the database is the ResponseID. How do I get the rest of the values to write to it?
This is a unique case where EditorFor could help. Essentially an object will have its editor template which is kind of like a partial view but specific to editing forms.
Secondly, the being form you are specifying is expecting the model of the view that you specified - in your case the viewWrapper. If for instance you specified a List<BasicLife>, then that is what the postBack shall be expecting, and not the BasicLife object. Below is how your postback would look like.
[HttpPost]
public ActionResult CreateBasicLifeResponse(List<BasicLife> model){
//your code goes here
}
From your view though, it looks clear that Model contains more than just a list. That is what shall be expected from the callback.

View doesn't recognize class in viewmodel

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.

Save List of object in MVC 5

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.

Query with linq from database

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

Resources