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

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

Related

ASP.NET MVC Route Parameter replacing Model Field

I am testing an ASP.NET MVC 5 application with Visual Studio 2017 Community edition.
I am trying to save Assort model to database with following code.
I am navigating to Assort Create page with URL /Assort/Create/1A.
The parameter 1A is needed on create page of Assort as I need to display some additional information from that parameter on create page itself.
But when I submit the data, 1A parameter value is being inserted as ID value of Assort model, and thus my ModelState is invalid and I am unable to save data.
Can anyone help me?
MODEL
public class Assort
{
[Key]
public int ID { get; set; }
[Display(Name = "Assort No")]
[Required(ErrorMessage = "Assort No can not be empty.")]
public int ASSORTNO { get; set; }
[Display(Name = "Date")]
[Required(ErrorMessage = "Date can not be empty.")]
public DateTime DATE { get; set; }
[Display(Name = "RFNO")]
[Required(ErrorMessage = "RFNO can not be empty.")]
[StringLength(50)]
public string RFNO { get; set; }
[Display(Name = "Manager")]
[Required(ErrorMessage = "Manager can not be empty.")]
public int MANAGER { get; set; }
[Display(Name = "Caret")]
[Required(ErrorMessage = "Caret can not be empty.")]
public decimal CARET { get; set; }
[Display(Name = "MFG Size")]
[Required(ErrorMessage = "MFG Size can not be empty.")]
public decimal MFGSIZE { get; set; }
[Display(Name = "Total PCS")]
[Required(ErrorMessage = "Total PCS can not be empty.")]
public decimal TOTALPCS { get; set; }
[StringLength(50)]
public string APPROVALSTATUS { 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; }
[UIHint("AssortReturn")]
public virtual List<AssortReturn> AssortReturn { get; set; }
public Assort()
{
AssortReturn = new List<AssortReturnModel.AssortReturn>();
}
[ForeignKey("RFNO")]
public virtual Rough rough { get; set; }
}
ACTION
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Assort assort)
{
if (ModelState.IsValid)
{
assort.APPROVALSTATUS = "NOT APPROVED";
assort.CREATE_TIMESTAMP = DateTime.Now;
assort.LAST_EDIT_TIMESTAMP = DateTime.Now;
db.Assorts.Add(assort);
db.SaveChanges();
return RedirectToAction("Index");
}
Initialize(assort.RFNO,"CREATE");
return View(assort);
}
VIEW
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ASSORTNO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ASSORTNO, new { htmlAttributes = new {#readonly="readonly",#Value=ViewBag.ASSORTNO, #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ASSORTNO, "", 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.EditorFor(model => model.DATE, new { htmlAttributes = new {#autofocus="autofocus",#Value=ViewBag.CURRENTDATE, #class = "form-control date" } })
#Html.ValidationMessageFor(model => model.DATE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RFNO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RFNO, new { htmlAttributes = new { #readonly = "readonly", #Value = ViewBag.RFNO, #class = "form-control" } })
#Html.TextBox("AVAILABLECARET",(decimal)ViewBag.AVAILABLECARET,new {#class="form-control txtAvailablecaret",#readonly="readonly" })
#Html.ValidationMessageFor(model => model.RFNO, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MANAGER, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.MANAGER, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.DropDownListFor(model => model.MANAGER, new SelectList(ViewBag.MANAGERLIST, "ID", "USERNAME"), "Select Manager", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MANAGER, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CARET, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CARET, new { htmlAttributes = new { #class = "form-control txtCaret" } })
#Html.ValidationMessageFor(model => model.CARET, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MFGSIZE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MFGSIZE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MFGSIZE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TOTALPCS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TOTALPCS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TOTALPCS, "", 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 class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default btnCreate" />
</div>
</div>
</div>
}
This is because of the default route, which is handling your request. It looks like:
{controller}/{action}/{id}
And so A1 gets bound to ID. If you want a different behavior, say A1 is still a part of the URL, but binds to a different param, say "name", you need a new route for that:
routes.MapRoute(
name: "CreateAssort",
url: "Assort/Create/{name}",
defaults: new { controller = "Assort", action = "Create"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Now "name" will hold A1 and not ID. Notice how your custom route comes before the default one. This is important - routing picks the first route that matches the request.
What you can do is add a hidden input field named ID to your view.
When the form will be submitted, the value from this field will take precedence over the one from your route i.e. '1A' and the model would have ID as 0 if you don't set the hidden input's value.
I had same issue. But problem is when you creating an model.
You need to have two methods.
[HttpGet] // http://localhost/Assort/Create/1
public ActionResult Create(int Id)
{
ModelState.Remove(nameof(Id)); // this will remove binding
var assort = new Assort()
{
Id = 'whatever',
....
};
return View(assort);
}
[HttpPost] // http://localhost/Assort/Create/
public ActionResult Create(Models.Assort assort)
{
if (ModelState.IsValid)
{
assort.APPROVALSTATUS = "NOT APPROVED";
assort.CREATE_TIMESTAMP = DateTime.Now;
assort.LAST_EDIT_TIMESTAMP = DateTime.Now;
db.Assorts.Add(assort);
db.SaveChanges();
return RedirectToAction("Index");
}
Initialize(assort.RFNO,"CREATE");
return View(assort);
}
C# ASP MVC Route Model ID bug

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

How create single create action for multiple models with TPH approach

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

Resources