I'm struggling to solve a problem in relation to foreign keys.
Scenario: I'm building a very basic wrestling simulator game.
Some of the model classes that I have are:
public class Wrestler
{
public int WrestlerId { get; set; }
public string Name { get; set; }
public int Overall { get; set; }
public string Finisher { get; set; }
public virtual ICollection<Match> Matches { get; set; }
}
public class Show
{
public int ShowId { get; set; }
public string Name { get; set; }
public int PromotionId {get; set;}
public int MatchId { get; set; }
public virtual ICollection<Match> Matches { get; set; }
public virtual Promotion Promotion { get; set; }
}
public class Promotion
{
public int PromotionId { get; set; }
public string Name { get; set; }
public decimal Budget { get; set; }
public string Size { get; set; }
public virtual ICollection<Championship> Championship { get; set; }
}
public class Championship
{
public int ChampionshipId { get; set; }
public string Name { get; set; }
public string Prestige { get; set; }
public int PromotionId { get; set; }
public virtual Promotion Promotion { get; set; }
}
The problem: I would like to add the functionality to create a Wrestling Match using a simple drop-down style form to select two wrestlers to face off and also to decide a winner, however, I can't figure out how to do this.
Here is what I have so far.
public class Match
{
public int MatchId { get; set; }
public int WrestlerId { get; set; }
public int WrestlerTwoId { get; set; }
public int WinnerId { get; set; }
public int ShowId { get; set; }
public virtual Wrestler Wrestler { get; set; }
public virtual Show Show { get; set; }
}
WrestlerId should be for example Hulk Hogan (WrestlerId = 1), and WrestlerTwoId should be "The Rock" (WrestlerTwoId = 2) and let's say Hulk Hogan is the winner so (WinnerId=1)
So how do I build a drop-down, like:
enter image description here
Here is the create view, Note, I know it may be incorrect
<div class="form-horizontal">
<h4>Match</h4>
<div class="form-group">
<label class="control-label col-md-2" for="Wrestler">Wrestler</label>
<div class="col-md-10">
#Html.DropDownList("WrestlerId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.WrestlerId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="Wrestler">Wrestler</label>
<div class="col-md-10">
#Html.DropDownList("WrestlerTwoId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.WrestlerTwoId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="Winner">Winner</label>
<div class="col-md-10">
#Html.DropDownList("WinnerId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.WinnerId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="Show">Show</label>
<div class="col-md-10">
#Html.DropDownList("ShowId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ShowId, "", new { #class = "text-danger" })
</div>
</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>
And here is the create action on the match controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MatchId,WrestlerId,WrestlerTwoId,WinnerId,ShowId")]Match match)
{
try
{
if (ModelState.IsValid)
{
db.Matches.Add(match);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
PopulateShowsDropDownList(match.ShowId);
return View(match);
}
Also if needed, here is the context class:
public class WrestlingContext : DbContext
{
public DbSet<Wrestler> Wrestlers { get; set; }
public DbSet<Promotion> Promotions { get; set; }
public DbSet<Championship> Championships { get; set; }
public DbSet<Match> Matches { get; set; }
public DbSet<Show> Shows { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
I have searched high and low, with this answer being the closest to what I thought I needed, but it didn't seem to work.
I really appreciate the feedback as this is a difficult one for me to solve.
Related
I am using EF and my relationship between tables is many-to-many. I want to display and edit the ICollection property to not only display my ingredients from a recipe, but to also edit, add, or delete them.
I tried to use EditorFor, but the changes of the ingredient were never changed and submitted to the database. I want to use DropDownList because it can show the ingredients that my recipe has in a list format so I can choose between them.
This is my Recipe and Ingredients Model with the relational table RecipesIngredients:
namespace Licenta.Models
{
public class Recipe
{
[Key]
public int IDRecipe { get; set; }
public string Name { get; set; }
public string Desc { get; set; }
public string Steps { get; set; }
public float Kcal { get; set; }
public float Pro { get; set; }
public float Carbo { get; set; }
public float Fat { get; set; }
public virtual ICollection<RecipesIngredients> RecipesIngredients { get; set; }
}
}
namespace Licenta.Models
{
public class RecipesIngredients
{
[Key]
[Column(Order = 1)]
public int IDRecipe { get; set; }
[Key]
[Column(Order = 2)]
public int IDIngredient { get; set; }
public virtual Recipe Recipe { get; set; }
public virtual Ingredient Ingredient { get; set; }
}
}
namespace Licenta.Models
{
public class Ingredient
{
[Key]
public int IDIngredient { get; set; }
public string Nume { get; set; }
public float Kcal { get; set; }
public float Pro { get; set; }
public float Carbo { get; set; }
public float Fat { get; set; }
public virtual ICollection<RecipesIngredients> RecipesIngredients { get; set; }
}
}
This is my Controller:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Recipe recipe = db.Recipes.Find(id);
if (recipe == null)
{
return HttpNotFound();
}
return View(recipe);
}
// POST: Recipes/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "IDRecipe,Name,Kcal,Pro,Carbo,Fat,Desc,Steps,Ingredients,RecipesIngredients")] Recipe recipe)
{
if (ModelState.IsValid)
{
db.Entry(recipe).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(recipe);
}
And the View of the Edit page:
#model Licenta.Models.Recipe
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Rețetă</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.IDRecipe)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#foreach (var item in Model.RecipesIngredients)
{
<td>
#Html.DropDownListFor(model => item.Ingredient.Nume, #* this is where i want to edit the ingredients*#)
</td>
}
<div class="col-md-10">
#Html.ValidationMessageFor(model => model.RecipesIngredients, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
That is the View that I want to use to edit my ingredients. Is there any way to do that?
This section creates job offers (it is a job portal), from which, you need to choose Area and Subarea. When I select an Area, I should see the Subareas of that Area. I leave an image to see the composition of the tables:
tables area & subarea
My job offer model is this:
namespace ProyectoBase4.Models
{
using System;
using System.Collections.Generic;
public partial class OfertaLaboral
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public OfertaLaboral()
{
this.OfertaPostulante = new HashSet<OfertaPostulante>();
}
public int Of_ID { get; set; }
public Nullable<int> OfEmp_ID { get; set; }
public string Of_Titulo { get; set; }
public string Of_Puesto { get; set; }
public Nullable<int> Of_Area { get; set; }
public Nullable<int> Of_Subarea { get; set; }
public string Of_Descrp { get; set; }
public string Of_Lugar { get; set; }
public Nullable<int> Of_Vacante { get; set; }
public Nullable<System.DateTime> Of_FechaIn { get; set; }
public Nullable<System.DateTime> Of_FechaFin { get; set; }
public Nullable<int> Of_Salario { get; set; }
public Nullable<int> Of_Jornada { get; set; }
public Nullable<int> Of_Mov { get; set; }
public Nullable<int> Of_Edu { get; set; }
public Nullable<int> Of_TContrato { get; set; }
public Nullable<int> Of_Estado { get; set; }
public virtual Area Area { get; set; }
public virtual Educacion Educacion { get; set; }
public virtual Estado Estado { get; set; }
public virtual Jornada_Compl Jornada_Compl { get; set; }
public virtual Movilidad Movilidad { get; set; }
public virtual Subarea Subarea { get; set; }
public virtual TipoContrato TipoContrato { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<OfertaPostulante> OfertaPostulante { get; set; }
}
}
How can I do that by choosing a field in Area, I display the corresponding Subtareas? This is the view:
<div class="">
<div class="form-group col-md-8">
#Html.LabelFor(model => model.Of_Titulo, htmlAttributes: new { style = "" })
<div class="">
#Html.EditorFor(model => model.Of_Titulo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Of_Titulo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group col-md-3">
#Html.LabelFor(model => model.Of_Area, htmlAttributes: new { #class = "", style = "margin-left:10px;" })
<div class="">
#Html.DropDownList("Of_Area", null, htmlAttributes: new { #class = "form-control form-control-75", style = "margin-left:10px;" })
#Html.ValidationMessageFor(model => model.Of_Area, "", new { #class = "text-danger" })
</div>
</div>
</div>
<br /><br /><br /><br />
<div>
<div class="form-group col-md-4">
#Html.LabelFor(model => model.Of_Vacante, htmlAttributes: new { #class = "" })
<div class="">
#Html.EditorFor(model => model.Of_Vacante, new { htmlAttributes = new { #class = "form-control form-control-50" } })
#Html.ValidationMessageFor(model => model.Of_Vacante, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group col-md-4">
#Html.LabelFor(model => model.Of_Salario, htmlAttributes: new { #class = "" })
<div class="">
#Html.EditorFor(model => model.Of_Salario, new { htmlAttributes = new { #class = "form-control form-control-50" } })
</div>
</div>
<div class="form-group col-md-3">
#Html.LabelFor(model => model.Of_Subarea, htmlAttributes: new { #class = "", style = "margin-left:40px;" })
<div class="">
#Html.DropDownList("Of_Subarea", null, htmlAttributes: new { #class = "form-control form-control-75", style = "margin-left:40px;" })
#Html.ValidationMessageFor(model => model.Of_Subarea, "", new { #class = "text-danger" })
</div>
</div>
As I mentioned before, I need that when I choose an option, then when I select the sub-option, only the options of that area appear to me.
Example:
view
Thanks
First, add an attribute to the subarea options with the area.
An example can be found here: SelectListItem with data-attributes
Second, handle the change() event of the area drop-down in jQuery. Use that event handler to hide() all options not in that area, and show() those that are.
$("#Of_Area").change(function(){
$("#Of_Subarea>option").hide();
$("#Of_Subarea>option[area=" + $("#Of_Area>option:selected").attr("value") + "]").show();
});
I have the following table:
And the model for it:
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public int Duration { get; set; }
public enum Ratings
{
G = 1,
PG = 2,
PG13 = 3,
R = 4
}
public virtual Ratings MaturityRating { get; set; }
public ICollection<Screening> Screenings { get; set; }
}
In my Screening model I want to reference one of the movies so I can add a Screening:
public class Screening
{
public int Id { get; set; }
public DateTime Date { get; set; }
public int Room { get; set; }
public int Seats { get; set; }
[ForeignKey("Movie")]
public virtual int MovieId { get; set; }
public virtual Movie Movie { get; set; }
}
The problem is, the scaffolded form displays the movies in the drop-down with their ids, and it should be with their titles:
How can I change that?
Create a List in the controller to populate the dropdown. It the ViewBag Object name matches the Model property name it will be used for the dropdown items.
View
#*DropDownList*#
<div class="form-group">
#Html.LabelFor(model => model.Movie, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Movie, null, "Please Select", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Movie, "", new { #class = "text-danger" })
</div>
</div>
Controller Action, include
ViewBag.Movie = db.Movies.GetAll().Select(x=> new SelectListItem() { Name = x.Name, Value x.Id});
I have a view model for a view AddAppointment. It has many properties of which 2 are Required (I wrote Required attribute over it).
Now I want to use the same model for another view but excluding the properties which are required but it doesn't work i.e. it's invalid.
What to do apart from writing another view model?
View Model:
public class AddBookingsViewModel
{
public string CustomerName { get; set; }
public string ContactNo { get; set; }
public string VehicleRegNo { get; set; }
public short fk_VehicleMakeID { get; set; }
public string VehicleModel { get; set; }
[Required(ErrorMessage = "Select appointment time ")]
public int fk_TimeSlotID { get; set; }
public byte fk_BookingModeID { get; set; }
public int EntryUserID { get; set; }
public int ReturnBookingID { get; set; }
[Required(ErrorMessage="Fill in the appointment date")]
[DataType(DataType.Date)]
public DateTime? AppointmentDate { get; set; }
}
View: (Where it is used)
#model ZahidCarWash.ViewModels.AddBookingsViewModel
#{
ViewBag.Title = "Add Appointment";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!-- page banner -->
<!-- end page banner -->
#using (Html.BeginForm())
{
<!-- appointments -->
<div id="appointments" class="appointment-main-block appointment-two-main-block">
<div class="container">
<div class="row">
<div class="section text-center">
<h3 class="section-heading text-center">Get an Appointment</h3>
</div>
<div class="col-md-8 col-sm-12">
<div class="appointment-block">
<h5 class="form-heading-title"><span class="form-heading-no">1.</span>Vehicle Information</h5>
<div class="row">
<div class="col-sm-4">
<div class="dropdown">
#Html.DropDownListFor(Model => Model.fk_VehicleMakeID, new SelectList(ZahidCarWash.DAL.VehicleMakesRepository.getVehicleMakes(), "VehicleMakeID", "MakeTitle"),
new { #class = "form-control" })
</div>
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.VehicleModel, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Vehicle Model" } })
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.VehicleRegNo, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Vehicle Reg No." } })
</div>
</div>
<h5 class="form-heading-title"><span class="form-heading-no">2.</span>Contact Details</h5>
<div class="row">
<div class="col-sm-4">
#Html.EditorFor(Model => Model.CustomerName, new { htmlAttributes = new { #class = "form-control", placeholder = "Customer Name" } })
#Html.ValidationMessageFor(Model => Model.CustomerName, "", new { #class = "ErrorMessages" })
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.ContactNo, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Contact Number." } })
#Html.ValidationMessageFor(Model => Model.ContactNo, "", new { #class = "ErrorMessages" })
</div>
</div>
<button type="submit" class="btn btn-default pull-right">Book Now</button>
</div>
</div>
</div>
</div>
</div>
}
Controller:
public JsonResult AddManualAppointment(AddBookingsViewModel AddBookingVM)
{
if (ModelState.IsValid)
{
AddBookingVM.fk_BookingModeID = 2;
int ReturnRowsCount = BookingRep.InsertCustomerAppointments(AddBookingVM, out ReturnStatus, out ReturnMessage, out ReturnBookingID);
}
else
{
}
return Json(new { ReturnMessageJSON = ReturnMessage, ReturnStatusJSON = ReturnStatus });
}
Data is passed through ajax:
<script type="text/javascript">
//to add an appointment
$('form').submit(function (e) {
e.preventDefault();
if (!$(this).valid()) {
return;
}
var url = '#Url.Action("AddManualAppointment")';
var data = $(this).serialize();
$.post(url, data, function (response) {
if (response.ReturnStatusJSON == true) {
swal("Booked !", response.ReturnMessageJSON, "success");
$("#VehicleRegNo").val("");
$("#VehicleModel").val("");
$("#CustomerName").val("");
$("#ContactNo").val("");
}
else {
swal("Sorry !", response.ReturnMessageJSON, "error");
}
});
});
</script>
<!--End Custom Scripts-->
}
I guess the quick and dirty way is to use #Html.Hiddenfor and fill the value with a new datetime from inside your controller
You can split your view model into a version with and without the required attributes using inheritance:
public class AddBookingsViewModel
{
public string CustomerName { get; set; }
public string ContactNo { get; set; }
public string VehicleRegNo { get; set; }
public short fk_VehicleMakeID { get; set; }
public string VehicleModel { get; set; }
public byte fk_BookingModeID { get; set; }
public int EntryUserID { get; set; }
public int ReturnBookingID { get; set; }
}
public class AddBookingsViewModelWithAppointment : AddBookingsViewModel
{
[Required(ErrorMessage = "Select appointment time ")]
public int fk_TimeSlotID { get; set; }
[Required(ErrorMessage="Fill in the appointment date")]
[DataType(DataType.Date)]
public DateTime? AppointmentDate { get; set; }
}
This allows you to use the appropriate view model in your situation and still maintain compatibilty through polymorphism.
If you need the optional properties in your base class, you can make your properties virtual and apply the attribute in the derived class:
public class AddBookingsViewModel
{
public string CustomerName { get; set; }
public string ContactNo { get; set; }
public string VehicleRegNo { get; set; }
public short fk_VehicleMakeID { get; set; }
public string VehicleModel { get; set; }
public byte fk_BookingModeID { get; set; }
public int EntryUserID { get; set; }
public int ReturnBookingID { get; set; }
public virtual int fk_TimeSlotID { get; set; }
public virtual DateTime? AppointmentDate { get; set; }
}
public class AddBookingsViewModelWithAppointment : AddBookingsViewModel
{
[Required(ErrorMessage = "Select appointment time ")]
public override int fk_TimeSlotID {
get => base.fk_TimeSlotID;
set => base.fk_TimeSlotID = value;
}
[Required(ErrorMessage="Fill in the appointment date")]
[DataType(DataType.Date)]
public override DateTime? AppointmentDate {
get => base.AppointmentDate;
set => base.AppointmentDate = value;
}
}
Use the veriant that works best in your business case.
I'm calling three Models (Unit, Site, Work_Type) in my view model called UnitAdminViewModel. I need to set one field as required from the Unit Model. Since I'm using Database First approach, I cannot modify the Unit Model directly since this gets autogenerated. How can I successfully add:
[Required(ErrorMessage = "Group is required")]
public string GroupName { get; set; }
to my view model UnitAdminViewModel?
public class UnitAdminViewModel
{
public Unit Unit { get; set; }
public List<Site> Site { get; set; }
public IEnumerable<Work_Type> Work_Type { get; set; }
}
In the Unit Model, I want to set the field GroupName as [Required]
public partial class Unit
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Unit()
{
this.Staffs = new HashSet<Staff>();
}
public int UnitID { get; set; }
public string UnitCode { get; set; }
public string UnitName { get; set; }
public string GroupName { get; set; }
public byte IncentiveUnit { get; set; }
public bool CallCenter { get; set; }
public bool CDWUnit { get; set; }
public string CDWSite { get; set; }
public Nullable<int> SiteID { get; set; }
public Nullable<int> DivisionID { get; set; }
public bool WFCUnit { get; set; }
public bool QAMonitored { get; set; }
public bool NICEMonitored { get; set; }
public string ListPrefix { get; set; }
public string TSHSource { get; set; }
public string StatsSource { get; set; }
public string DialerSource { get; set; }
public Nullable<int> CostCenterID { get; set; }
public int WaterfallView { get; set; }
public bool Locked { get; set; }
public string Platform { get; set; }
public Nullable<int> Supplier { get; set; }
public string Work_Type { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Staff> Staffs { get; set; }
}
Update
I tried going off #Izzy example. I feel like i'm closer, but the [Required] still doesn't seem to trigger a validation error when I submit a form without populating that field. #Izzy, is there something I might be missing?
View Model
public class UnitAdminViewModel
{
public Unit Unit { get; set; }
public List<Site> Site { get; set; }
public IEnumerable<Work_Type> Work_Type { get; set; }
}
UnitMetaData class
[MetadataType(typeof(UnitMetaData))]
public partial class Unit
{
}
public class UnitMetaData {
[Required(ErrorMessage = "Group is required")]
public string GroupName { get; set; }
[Required(ErrorMessage = "UnitName is required")]
public string UnitName { get; set; }
public string CDWSite { get; set; }
public string Platform { get; set; }
public Nullable<int> Supplier { get; set; }
public string Work_Type { get; set; }
}
VIEW
#model WebReportingToolDAL.Models.ViewModels.UnitAdminViewModel
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Unit</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Unit.UnitName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Unit.UnitName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Unit.UnitName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Unit.GroupName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Unit.GroupName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Unit.GroupName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Unit.CDWSite, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Unit.CDWSite, new SelectList(Model.Site, "SiteName", "SiteName"), new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Unit.Platform, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Unit.Platform, new List<SelectListItem> { new SelectListItem { Text = "PSCC", Value = "PSCC" }, new SelectListItem { Text = "RC", Value = "RC" } }, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Unit.Supplier, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Unit.Supplier, new List<SelectListItem> { new SelectListItem { Text = "0", Value = "0" }, new SelectListItem { Text = "1", Value = "1" } }, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Unit.Work_Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Unit.Work_Type,new SelectList(Model.Work_Type, "Name", "Name"),new { #class = "form-control" })
</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>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "UnitID,UnitCode,UnitName,GroupName,IncentiveUnit,CallCenter,CDWUnit,CDWSite,SiteID,DivisionID,WFCUnit,QAMonitored,NICEMonitored,ListPrefix,TSHSource,StatsSource,DialerSource,CostCenterID,WaterfallView,Locked,Platform,Supplier,Work_Type")] Unit unit)
{
if (ModelState.IsValid)
{
unit.UnitCode = "XX";
unit.IncentiveUnit = 1;
unit.CallCenter = true;
unit.CDWUnit = true;
unit.DivisionID = 2;
unit.WFCUnit = false;
unit.QAMonitored = false;
unit.NICEMonitored = true;
unit.ListPrefix = null;
unit.TSHSource = null;
unit.StatsSource = null;
unit.DialerSource = null;
unit.CostCenterID = 3;
unit.WaterfallView = 1;
unit.Locked = false;
var siteId = (from s in db.Sites
where s.SiteName.ToLower().Equals(unit.CDWSite.ToLower())
select s.SiteID).First();
unit.SiteID = siteId;
db.Units.Add(unit);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(unit);
}
When using Database first approach you'll realise that the class is marked as partial So what you can do is make use of MetadataType attribute to achieve what you're after.
So go ahead and create a file and name it e.g. UnitMetaData. Your code should look something like:
public class UnitMetaData
{
[Required(ErrorMessage = "Group is required")]
public string GroupName { get; set; }
//more properties
}
Your Unit class is partial so you can create it another file and use MetadataType as:
[MetadataType(typeof(UnitMetaData))]
public partial class Unit
{
}
More about MetadataType here
partial definition:
It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.
source
Please Note: Ensure the namespace is same as the generated Unit class, otherwise it will not work
You can use a real view model, for one. Simply wrapping a bunch of entities in a class is missing the point of what view models are for. Your view models should only contain the properties that should be displayed/edited and it should hold the business logic for your view, such as the fact that GroupName is required (when it apparently isn't at the database level).
That means creating something like:
public class UnitViewModel
{
// other properties you want to edit
[Required]
public string GroupName { get; set; }
}
Then, you use this rather than Unit in your view, and map the posted properties from UnitViewModel onto your Unit instance.