MVC - Foreign Key Error because of ViewModel? - asp.net-mvc-4

I am Creating View Model of Employee Class and strongly typed my Create View with the EmployeeViewModel. In future, I will add many classes in my View Model. But the problem is I am getting Gender Foreign Key Error. May be I am binding wrong values in Create Controller. Below is my code:
Create Controllers:
public ActionResult Create()
{
ViewBag.GenderId = new SelectList(db.Genders, "Id", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EmployeeViewModel employeeModel)
{
if (ModelState.IsValid)
{
db.Employees.Add(employeeModel.Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.GenderId = new SelectList(db.Genders, "Id", "Name", employeeModel.Employee.GenderId);
return View(employeeModel);
}
Create View:
#model WebApplication2.EmployeeViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Employee.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.GenderId, "GenderId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("GenderId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Employee.GenderId, "", 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>
}
Models:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public byte GenderId { get; set; }
public Gender Gender { get; set; }
}
public class Gender {
public byte Id { get; set; }
public string Name { get; set; }
}
View Model:
public class EmployeeViewModel
{
public Employee Employee { get; set; }
}

Related

Getting some input from user and insert multiple table with Entity Framework

I want to add some information into my database. The question is how can I post my inputs for 3 table at the same time? My tables are below. Let me clear that.
I have teachers and working hours and working days. I want that firstly I select the teacher name from dropdownlist,then select the day from dropdownlist and write working hours for example "09:00 - 17:00".
After that I submit these information I expectation is that seeing all these information can be added into database seperately and relationally.
Sample scenario: John Reese Friday 09:00-17:00
Harold Finch Monday 11:00-15:00
I am able to pull the teacher's names from database but at the same time in the same page I want to see that day's names. After all these selecetions as I mentioned above, I wanna add all these informations.
My create controller
public ActionResult Create()
{
var myTeacherList = (from teacher in db.Teachers.ToList()
select new SelectListItem
{
Text = teacher.Firstname + teacher.Lastname,
Value = teacher.Id.ToString(),
}).ToList();
var myDayNameList = (from day in db.WeekDays.ToList()
select new SelectListItem
{
Text = day.Name,
Value = day.Id.ToString(),
}).ToList();
ViewBag.TeacherId = myTeacherList;
ViewBag.DayId = myDayNameList;
return View();
}
My Create Controller
<div class="form-horizontal">
<h4>Appointment</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.TeacherId, "Teacher Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m=>m.Teacher.Id,(List<SelectListItem>)ViewBag.TeacherId, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TeacherId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Hours,"Working Hour", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Hours, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Hours, "", 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>
}
Teacher.cs
namespace LanguageSchool.Models
{
using System;
using System.Collections.Generic;
public partial class Teacher
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Teacher()
{
this.Appointments = new HashSet<Appointment>();
this.Classes = new HashSet<Class>();
this.Languages = new HashSet<Language>();
}
public int Id { get; set; }
public string Description { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public System.DateTime DateOfStart { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Appointment> Appointments { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Class> Classes { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Language> Languages { get; set; }
}
}
Appointment.cs
namespace LanguageSchool.Models
{
using System;
using System.Collections.Generic;
public partial class Appointment
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Appointment()
{
this.WeekDays = new HashSet<WeekDay>();
}
public int Id { get; set; }
public int TeacherId { get; set; }
public string Hours { get; set; }
public virtual Teacher Teacher { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<WeekDay> WeekDays { get; set; }
}
}
WeekDay.cs
namespace LanguageSchool.Models
{
using System;
using System.Collections.Generic;
public partial class WeekDay
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public WeekDay()
{
this.Class_WeekDay = new HashSet<Class_WeekDay>();
this.Appointments = new HashSet<Appointment>();
}
public int Id { get; set; }
public string Name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Class_WeekDay> Class_WeekDay { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Appointment> Appointments { get; set; }
}
}
We need to make a ViewModel that contains all those properties so that the moment we do a POST request, they are all bound and we could access them for saving.
But first we need to modify your models and insert a class for the many to many table.
We need to remove Weekday from Appointments and
Appointments from Weekday.
Then replace them with AppointmentWeekday. Be sure to run Migrations/Update-Database after this first step.
public class Appointment{
...
// REMOVE public virtual ICollection<WeekDay> WeekDays { get; set; }
// Add this
public virtual ICollection<AppointmentWeekday> AppointmentWeekdays {get;set;}
}
public class Weekday{
...
// REMOVE public virtual ICollection<Appointment> Appointments { get; set; }
// Add this
public virtual List<AppointmentWeekday> AppointmentWeekdays {get;set;}
}
// Add this
public class AppointmentWeekday{
public int AppointmentId {get;set;}
[ForeignKey("AppointmentId")]
public virtual Appointment Appointment {get;set;}
public int WeekdayId {get;set;}
[ForeignKey("WeekdayId")]
public virtual Weekday Weekday {get;set;}
}
Make the View Model with the necessary properties, I named it TeacherAppointmentViewModel.
public class TeacherAppointmentViewModel{
public int TeacherId {get;set;}
public int DayId {get;set;}
public string Hours {get;set;}
}
Instantiate this in your controller and pass it to the view.
public ActionResult Create()
{
var myTeacherList = (from teacher in db.Teachers.ToList()
select new SelectListItem
{
Text = teacher.Firstname + teacher.Lastname,
Value = teacher.Id.ToString(),
}).ToList();
var myDayNameList = (from day in db.WeekDays.ToList()
select new SelectListItem
{
Text = day.Name,
Value = day.Id.ToString(),
}).ToList();
ViewBag.TeacherId = myTeacherList;
ViewBag.DayId = myDayNameList;
// instantiate
TeacherAppointmentViewModel tvm = new TeacherAppointmentViewModel();
// pass to the view
return View(tvm);
}
Make your view use TeacherAppointmentViewModel.
#model TeacherAppointmentViewModel
Edit view, use the code below.
<div class="form-horizontal">
<h4>Appointment</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.TeacherId, "Teacher Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m=>m.TeacherId,(List<SelectListItem>)ViewBag.TeacherId, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TeacherId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.WeekdayId, "Day", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m=>m.WeekdayId,(List<SelectListItem>)ViewBag.WeekdayId, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.WeekdayId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Hours,"Working Hour", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Hours, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Hours, "", 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>
Use controller action below, we need to assign the properties to Appointment and AppointmentWeekday then add to the db;
[HttpPost]
public ActionResult Create(TeacherAppointmentViewModel tvm){
// create appointment
Appointment a = new Appointment();
// assign teacher id and hours from viewmodel
a.TeacherId = tvm.TeacherId;
a.Hours = tvm.Hours;
// save appointment
db.Appointments.Add(a);
db.SaveChanges();
// create appointmentweekday
AppointmentWeekday aw = new AppointmentWeekday();
// assign properties
// since we've saved the appointment, we could use a.AppointmentId
aw.WeekdayId = tvm.WeekdayId;
aw.AppointmentId = a.AppointmentId; // appointment from earlier
// save appointmentweekday
db.AppointmentWeekdays.Add(aw);
db.SaveChanges();
}

mvc model fileupadload does not send model data

I have a mvc 5 asp.net file upload that upload pictures and create path for them.
File uploaded successfully, but model data does comes in null.
This is my model:
[Table("Slider")]
public partial class Slider
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Slider()
{
Slider1 = new HashSet<Slider>();
}
public int ID { get; set; }
public string Path { get; set; }
public int? Slider_ID { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Slider> Slider1 { get; set; }
}
This is Controller part:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Path")] Slider slider, List<HttpPostedFileBase> FileContent)
{
if (ModelState.IsValid)
{
byte[] imageData = null;
if (Request.Files.Count > 0)
{
HttpPostedFileBase poImgFile = Request.Files["Path"];
using (var binary = new BinaryReader(poImgFile.InputStream))
{
imageData = binary.ReadBytes(poImgFile.ContentLength);
}
}
string picturePath = string.Format(Server.MapPath("~/content/slider/{0}.jpg"), slider.ID);
CreateDirectory(picturePath);
using (FileStream writer = new FileStream(picturePath, FileMode.Create))
{
writer.Write(imageData, 0, imageData.Length);
}
db.Sliders.Add(slider);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(slider);
}
And this is the view:
#using (Html.BeginForm("Create", "Sliders", FormMethod.Post, new { #class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="col-12 form-group">
<div class="row">
#Html.LabelFor(model => model.Path, "Picture", htmlAttributes: new { #class = "control-label col-12 col-md-2" })
<div class="col-12 col-md-10">
<input type="file" name="Path" id="fileUpload" accept=".png,.jpg,.jpeg,.gif" />
#Html.ValidationMessageFor(model => model.Path, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-12 text-left">
<input type="submit" value="create" class="btn btn-success" /> | #Html.ActionLink("back to list", "Index", null, new { #class = "btn btn-primary" })
</div>
</div>
</div>
}
When I check my database I see that Path is :
System.Web.HttpPostedFileWrapper
and Slider_ID is null and Slider_ID1 is null too.
Any suggestions?
After searching my previous codes, I've found that, when saving changes to db in controller class, db.SaveChanges(); slider argument which had been sent to Create method, will get new ID.
I've added these 2 lines after if:
if (ModelState.IsValid)
{
db.Sliders.Add(slider);
db.SaveChanges();
and done my other business logic in lines after that.

ASP.NET MVC - Object reference not set to an instance of an object in DropDownList

I have a model Class
public partial class FEES
{
public FEES()
{
}
public long FEE_ID { get; set; }
public decimal AMOUNT { get; set; }
public int CURRENCY_ID { get; set; }
public string NAME { get; set; }
public virtual CURRENCIES CURRENCIES { get; set; }
}
ViewModel
public class FeesViewModel
{
public SelectList CurrenciesList { get; set; }
public FeesViewModelInput input { get; set; }
public class FeesViewModelInput
{
[HiddenInput]
public long FEE_ID { get; set; }
[Display(Name = "Amount")]
[Required(ErrorMessage = "Fee Amount Is Required!")]
[RegularExpression(#"^[0-9,.]+$", ErrorMessage = "Please enter proper currency format e.g. 2,500")]
public decimal AMOUNT { get; set; }
[Display(Name = "Currency")]
[Required(ErrorMessage = "Currency Is Required!")]
public int CURRENCY_ID { get; set; }
[Required(ErrorMessage = "Fee Name Is Required!")]
[Display(Name = "Fee Name")]
public string NAME { get; set; }
}
}
Small service for the ViewModel
public void createFees(FEES fee, FeesViewModel viewModel)
{
fee.FEE_ID = viewModel.input.FEE_ID;
fee.CURRENCY_ID = viewModel.input.CURRENCY_ID;
fee.NAME = viewModel.input.NAME.Trim();
}
I call the service and the ViewModel in my controller.
Controller
public ActionResult Create()
{
FeesViewModel fees = new FeesViewModel();
fees.CurrenciesList = new SelectList(_currenciesService.GetCurrencies().Where(c => c.ACTION_STATUS != 2), "CURRENCY_ID", "CURRENCY_NAME");
fees.FeeTypesList = new SelectList(_feetypesService.GetFeeTypes().Where(c => c.ACTION_STATUS != 2), "FEE_TYPE_ID", "FEE_TYPE_NAME");
return View();
}
[HttpPost]
public ActionResult Create(FeesViewModel fees)
{
try
{
if (ModelState.IsValid)
{
//check if values is duplicate
if (_feesService.GetFees().Where(c => c.ACTION_STATUS != 2).Any(c => c.NAME.ToLower().Trim() == fees.input.NAME.ToLower().Trim()))
{
this.AddNotification("Fee Name already exist.<br/> Kindly verify the data.", NotificationType.ERROR);
}
else
{
var fee = new BPP.CCSP.Admin.Web.BPPCCSPAdminFeesService.FEES();
var helper = new FeesService();
helper.createFees(fee, fees);
_feesService.AddFee(fee);
var notif = new UINotificationViewModel()
{
notif_message = "Record saved successfully",
notif_type = NotificationType.SUCCESS,
};
TempData["notif"] = notif;
return RedirectToAction("Index");
}
}
}
catch (Exception e)
{
this.AddNotification("Fees cannot be added.<br/> Kindly verify the data.", NotificationType.ERROR);
}
fees.CurrenciesList = new SelectList(_currenciesService.GetCurrencies().Where(c => c.ACTION_STATUS != 2), "CURRENCY_ID", "CURRENCY_NAME");
return View(fees);
}
And the View
#model BPP.CCSP.Admin.Web.ViewModels.FeesViewModel
#{
//ViewBag.Title = "Create";
}
<div class=" box box-body box-primary">
#using (Html.BeginForm("Create", "Fees", FormMethod.Post, new { #class = "form-horizontal", #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, null, new { #class = "text-danger" })
#*#Html.HiddenFor(model => model.faculty_activation_date, new { #Value = System.DateTime.Now })*#
<div class="row .col">
<div style="margin-top:20px" class="mainbox col-md-12 col-md-offset-0 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Create Fee</div>
</div>
<div class="panel-body">
<div class="col-md-6">
<div>
#Html.LabelFor(model => model.input.NAME, "Fee Name")
#Html.TextBoxFor(model => model.input.NAME, new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = Html.DisplayNameFor(m => m.input.NAME), #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.input.NAME, null, new { #class = "text-danger" })
</div>
<div>
#Html.LabelFor(model => model.input.AMOUNT, "Amount")
#Html.TextBoxFor(model => model.input.AMOUNT, new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = Html.DisplayNameFor(m => m.input.AMOUNT), #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.input.AMOUNT, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div>
#Html.LabelFor(model => model.input.CURRENCY_ID, "Currency")
#*#Html.DropDownList("CURRENCY_ID", (IEnumerable<SelectListItem>)ViewBag.name, "Please Select a Currency", new { #class = "form-control", #style = "border-radius:3px;" })*#
#Html.DropDownListFor(x => x.input.CURRENCY_ID, Model.CurrenciesList, "Please Select a Currency", new { #class = "form-control", #style = "border-radius:3px;" })
#Html.ValidationMessageFor(model => model.input.CURRENCY_ID, null, new { #class = "text-danger" })
</div>
<div>
#Html.LabelFor(model => model.input.FEE_TYPE_ID, "Fee Type")
#Html.DropDownListFor(model => model.input.FEE_TYPE_ID, Model.FeeTypesList, "Please Select a Fee Type", new { #class = "form-control", #style = "border-radius:3px;" })
#Html.ValidationMessageFor(model => model.input.FEE_TYPE_ID, null, new { #class = "text-danger" })
</div>
</div>
</div>
<div class="panel-footer">
<div class="panel-title">
<div class="form-actions no-color">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
</div>
}
When I clicked on the View (Create), I got this error
The CurrencyID is a DropDownList coming from CURRENCIES model class.
I have these questions:
Why am I getting this error and how do I resolve it.
How do I do ViewModel without mapping.?
Why am I getting this error and how do I resolve it.
Because the Model is not set in your view. It is null.
When the users visit the Create page, you need to make sure to present them with options in the dropdown. Therefore, you need to make sure you pass the model into the view during GET.
public ActionResult Create()
{
// your code and pass fees to your view.
return View(fees);
}
How do I do ViewModel without mapping. Any example please.
You can use AutoMapper NuGet package to do the mapping.

IDENTITY_INSERT is set to OFF in MVC application

I am trying to create a new employee in MVC 5. I used CRUD to generate views and models. I edited a few lines of code and I get this error:
Cannot insert explicit value for identity column in table 'Table' when IDENTITY_INSERT is set to OFF.
Where I got this:
public ActionResult Create([Bind(Include = "Imie,Nazwisko,Pesel,Data_zatrudnienia,Data_zwolnienia,Pensja,Wyksztalcenie")] Osoba osoba,Pracownik pracownik)
{
if (ModelState.IsValid)
{
db.Osoba.Add(osoba);
db.Pracownik.Add(pracownik);
db.SaveChanges();
return RedirectToAction("Index");
}
My model class:
public partial class Pracownik
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id_osoby { get; set; }
public System.DateTime Data_zatrudnienia { get; set; }
public Nullable<System.DateTime> Data_zwolnienia { get; set; }
public double Pensja { get; set; }
public string Wyksztalcenie { get; set; }
public virtual Osoba Osoba { get; set; }
public virtual Pracownik_biurowy Pracownik_biurowy { get; set; }
public virtual Przewodnik Przewodnik { get; set; }
}
public partial class Osoba
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id_osoby { get; set; }
public string Imie { get; set; }
public string Nazwisko { get; set; }
public string Pesel { get; set; }
public virtual Pracownik Pracownik { get; set; }
}
Create form view:
#model BiuroPrototyp.Models.Pracownik
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Pracownik</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Osoba.Imie, htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.Osoba.Imie, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(model => model.Osoba.Imie, "", new {#class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Osoba.Nazwisko, htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.Osoba.Nazwisko, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(model => model.Osoba.Nazwisko, "", new {#class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Osoba.Pesel, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Osoba.Pesel, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Osoba.Pesel, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Data_zatrudnienia, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Data_zatrudnienia, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Data_zatrudnienia, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Pensja, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Pensja, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Pensja, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Wyksztalcenie, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Wyksztalcenie, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Wyksztalcenie, "", 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>
'Pracownik' class is employee and he is inherits from 'Osoba' which is Person in English. I dont know where I trying to put this id in my code.
You are trying to save an object to the database with an explicit ID set by you while the database is expecting to generate that value itself. That is the Id_osoby property in your object is set to something other than 0 and it is not identified to the EF framework as an identity field. If you want the Id to be generated by the database as your post suggests, then the corresponding property in the Object should be decorated with the [Key] attribute.

How to retrieve Posted file in create action of another entity

I am in trouble with a posted file related to an entity, I can see the posted file in the request, but if I add the httppostedfile as action parameter it will be null... what should I do to manage this case?
NewsArticle model:
public class NewsArticle
{
public string Title{get; set;}
public int ID{get; set;}
[AllowHtml]
public string Body { get; set; }
public Image Image { get; set; }
//other stuff
}
where the field Image is:
the related entity will be created in the newarticlecontroller
public class Image
{
public int ID { get; set; }
public string URL { get; set; }
public string Title { get; set; }
public string Subtitle { get; set; }
}
detail of view
#model GatorsWebSite.NewsArticle
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "NewsArticles", FormMethod.Post, new { enctype = "multipart/forma-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>NewsArticle</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Body, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Body, new { htmlAttributes = new { #class = "form-control ckHolder" } })
#Html.ValidationMessageFor(model => model.Body, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SubTitle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SubTitle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SubTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Image, new { type = "file" })
#Html.ValidationMessageFor(m => m.Image)
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.AuthorID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AuthorID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AuthorID, "", 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 { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
#Html.LabelFor(model => model.Published, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Published)
#Html.ValidationMessageFor(model => model.Published, "", 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>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/ckEditor")
<script type="text/javascript">
CKEDITOR.replace("#Html.IdFor(m => m.Body)", {});
</script>
}
Controller action:
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Title,Body,SubTitle,Published,Image")]NewsArticle newsArticle )// here I don't know how to manage the posted file
{
if (ModelState.IsValid)
{
newsArticle.Date = DateTime.Now;
newsArticle.AuthorID = User.Identity.GetUserId();
newsArticle.Body = newsArticle.Body;
_repository.Add(newsArticle);
return RedirectToAction("Index");
}
return View(newsArticle);
}
Any help will be really appreciated
And what if you put input file in your form like:
<div class="form-group">
<label for="newsimage">Select news image:</label>
<div class="col-md-10">
<div class="checkbox">
<input id="newsimage" type="file" name="newsimage"/>
</div>
</div>
</div>
and post action will be:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Title,Body,SubTitle,Published,Image")]NewsArticle newsArticle )// here I don't know how to manage the posted file
{
if (ModelState.IsValid)
{
string ImageUrl="";
for (int i = 0; i < Request.Files.Count; i++)
{
if (Request.Files[i].FileName!="")
{
string UrlFile = Server.MapPath("~/newsimagefolderpath/") + FileName;
Request.Files[i].SaveAs(UrlFile);
ImageUrl = UrlFile;
}
}
newsArticle.Date = DateTime.Now;
newsArticle.URL = string.IsNullOrEmpty(ImageUrl) ? "defaultimagepath" : ImageUrl;
newsArticle.AuthorID = User.Identity.GetUserId();
newsArticle.Body = newsArticle.Body;
_repository.Add(newsArticle);
return RedirectToAction("Index");
}
return View(newsArticle);
}
Ok, I am new to MVC so obviously I have to pay the tax, btw this is what I have done to solve this problem:
I have created a ViewModel to host the aggregated data of the view:
public class NewsArticleViewModel
{
public string Title { get; set; }
public int ID { get; set; }
[AllowHtml]
public string Body { get; set; }
public string SubTitle { get; set; }
public string AuthorID { get; set; }
public DateTime Date { get; set; }
public bool Published { get; set; }
public HttpPostedFileBase ImageUpload { get; set; }
}
then I have changed the signature of the control action:
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Title,Body,SubTitle,Published,ImageUpload")]GatorsWebSite.ViewModels.NewsArticleViewModel newsArticle)
then I have corrected a typo in the form declaration :)
#using (Html.BeginForm("Create", "NewsArticles", FormMethod.Post, new { enctype = "multipart/form-data" }))
...and then I have changed the view
#Html.LabelFor(model => model.ImageUpload, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.ImageUpload, new { type = "file" })
#Html.ValidationMessageFor(m => m.ImageUpload)
</div>
Result: