Selected value of selectlist is not set in #html.dropdownlistfor() in view - asp.net-mvc-4

controller action:
[HttpGet]
public ActionResult EditProject(int? id)
{
var project = _projectService.GetProjectById(id);
var selectedEngagementManager = _projectService.GetEmployeeById(project.EngagementManagerId);
var selectedProjectManager = _projectService.GetEmployeeById(project.ProjectManagerId);
ViewBag.EngageMentManagers = new SelectList(_projectService.GetAllEmployee(), "EmployeeId", "EmployeeId", selectedEngagementManager.EmployeeId);
ViewBag.ProjectManagers = new SelectList(_projectService.GetAllEmployee(), "EmployeeId", "EmployeeId", selectedProjectManager.EmployeeId);
return View(project);
}
view
<div class="form-group">
#Html.Label("Project Manager", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ProjectManagerId, (SelectList)ViewBag.ProjectManagers, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProjectManagerId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdditionalNotes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.AdditionalNotes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdditionalNotes, "", new { #class = "text-danger" })
</div>
</div>
here selected value is not going to displayed in dropdownlist in view..it just sselect last value in dropdownlist always

Related

Auto Adjust height of multiline editor for in MVC using bootstrap

I have below editorfor which is multiline, I need to auto adjust height when user starts adding multiple email address in separate lines using bootstrap. Any code example is highly appreciated.
Model:
[DataType(DataType.MultilineText)]
public string AdditionalEmailAddressesText { get; set; }
View:
<div class="form-group">
#Html.LabelFor(m => m.AdditionalEmailAddressesText, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
#Html.EditorFor(m => m.AdditionalEmailAddressesText, new { htmlAttributes = new { #class = "form-control", placeholder = #Strings.Porting_AdditionalEmailAddressesSubtext } })
#Html.ValidationMessageFor(m => m.AdditionalEmailAddressesText)
</div>
</div>
For textarea tag, there's no auto-height attribute to make it adjust the height automatically. And for the [DataType(DataType.MultilineText)] annotation, it doesn't provide feature for setting rows and colums as well. So you have to write script code to add oninput event listener to change the style.
#model NewEvent
<h1>#ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>
<div class="form-group">
#Html.LabelFor(m => m.Body, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
#Html.EditorFor(m => m.Body, new { htmlAttributes = new { #class = "form-control", placeholder = "placeholder" } })
#Html.TextAreaFor(model => model.Body, new {cols = 2, rows = 5})
#Html.ValidationMessageFor(m => m.Body)
</div>
</div>
#section scripts {
<script>
$("#Body").each(function () {
this.setAttribute("style", "height:" + (this.scrollHeight) + "px;overflow-y:hidden;");
}).on("input", function () {
this.style.height = "auto";
this.style.height = (this.scrollHeight) + "px";
});
</script>
}

MVC (Entity framework) Saving ID changes from "Create View" to SQL database table

I need solution for my problem. Got 1 database with 3 tables (with primary keys and identity (1,1) and 3 foreign keys) I will post diagram bellow.
My dropdown lists are connected if I choose Country it will just list me states from that country.
What I want to do is when i pick Country and state that automatically save their id in my table Contact. Because If I choose country and state Id manually it works otherwise I got error. Here are my controller code and Create View.
public ActionResult Create()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CountryStateContactViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
Contact model = new Contact() { CountryId = csvm.CountryId, StateId = csvm.StateId, ContactId = csvm.ContactsId, ImeOsobe = csvm.PersonName, PrezimeOsobe = csvm.PersonLastName, Komentar = csvm.Comment, Email = csvm.Email, Aktivan = csvm.Active, kcbr = csvm.kcbr, KucniBroj = csvm.HouseNumber, NazivUlice = csvm.StreetName, NazivNaselja = csvm.SettlementName, PostanskiBroj = csvm.PostalCode, KontaktBroj=csvm.ContactNumber};
db.Contacts.Add(model);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
}
And my CreateView
#model AkvizicijeApp_3_6.Models.CountryStateContactViewModel
<h2>Create</h2>
<br /><br />
<div class="container">
<div class="form-group">
#if (ViewBag.CountryList != null)
{
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select Country--", new { #class = "form-control" })
}
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { #class = "form-control" })
</div>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CountryId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StateId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PostalCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PostalCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PostalCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SettlementName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SettlementName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SettlementName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StreetName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StreetName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StreetName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HouseNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HouseNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HouseNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.kcbr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.kcbr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.kcbr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Active, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Active)
#Html.ValidationMessageFor(model => model.Active, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PersonName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PersonName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PersonName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PersonLastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PersonLastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PersonLastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContactNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContactNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comment, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comment, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comment, "", 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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value=`" + row.StateId + "`>" + row.StateName + "</option>")
});
});
})
});
</script>
public class CountryStateContactViewModel
{
public int CountryId { get; set; }
public int StateId { get; set; }
public string StateName { get; set; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContactsId { get; set; }
public int PostalCode { get; set; }
public string SettlementName { get; set; }
public string StreetName { get; set; }
public string HouseNumber { get; set; }
public string kcbr { get; set; }
public bool Active { get; set; }
public string PersonName { get; set; }
public string PersonLastName { get; set; }
public string ContactNumber { get; set; }
public string Email { get; set; }
public string Comment { get; set; }
}
If u need more information just tell me and I will update my question. Thanks alot.
Move your #Html.DropDownListFor inside #using (Html.BeginForm()). and remove StateId and CountryId manual input fields #Html.EditorFor(model => model.CountryId) & #Html.EditorFor(model => model.StateId). In other words replace "Html.EditorFor" with HtmlDropdownlistFor from above.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PostalCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PostalCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PostalCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SettlementName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SettlementName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SettlementName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StreetName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StreetName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StreetName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HouseNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HouseNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HouseNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.kcbr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.kcbr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.kcbr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Active, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Active)
#Html.ValidationMessageFor(model => model.Active, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PersonName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PersonName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PersonName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PersonLastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PersonLastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PersonLastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContactNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContactNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comment, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comment, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comment, "", 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>
}

File upload in MVC 5 when used in bootstrap modal returns null

I'm trying to allow file uploading on modal popup using bootstrap modal popup.
But it always returns null for type = "file"
I've tried following solutions but no luck:
File upload in MVC when used in bootstrap modal returns null
it always return null. If I run this directly as separate page then it works fine but only having problem with popup.
I tried to change the content type on ajax but then its giving me this error "required anti-forgery form field __requestverificationtoken is not present"
I've tested what does page post using development tools:
enter image description here
here are my codes:
controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Create([Bind(Include = "ID,FileName,Link,SourceType,Comments,SourceDate,DateCreated,DateModified,ProjectID")] ProjectSource projectSource, HttpPostedFileBase uploadFile)
{
if (ModelState.IsValid)
{
//upload method 1
var fileSavePath = "";
if (HttpContext.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Request.Files[0];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
fileSavePath = (HttpContext.Server.MapPath("~/xyz/") + httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
//upload method 2
if (uploadFile != null && uploadFile.ContentLength > 0)
{
try
{
string path = Path.Combine(Server.MapPath("~/xyz/"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
}
else
{
ViewBag.Message = "You have not specified a file.";
}
db.ProjectSources.Add(projectSource);
await db.SaveChangesAsync();
return " File : " + ViewBag.Message + " == " + fileSavePath;
}
return " File : " + ViewBag.Message +" === "+sb.ToString();
}
view:
#model CharterPortal.Models.ProjectSource
#{
Layout = "";
#Scripts.Render("~/Scripts/jquery-2.2.3.min.js")
#Scripts.Render("~/Scripts/moment.min.js")
#Scripts.Render("~/Scripts/bootstrap.min.js")
#Scripts.Render("~/Scripts/bootstrap-datetimepicker.min.js")
#Scripts.Render("~/Scripts/bootstrap.fd.js")
}
×
Add new Source
#using (Html.BeginForm("Create", "ProjectSource", FormMethod.Post, new { enctype = "multipart/form-data" , #id="ajaxForm"}))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
#*#Html.ValidationSummary(true, "", new { #class = "text-danger" })*#
<div class="form-group">
#Html.Label("Source file", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.FileName, new { htmlAttributes = new { #class = "form-control" } })
#*<input type="file" name="uploadFile" />*#
#Html.TextBox("uploadFile",null, new { #class = "form-control", type = "file" })
#*Add file*#
#Html.ValidationMessageFor(model => model.FileName, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
<div class="col-md-10" id="files" style="padding-left:40px;">
</div>
</div>*#
<div class="form-group">
#Html.LabelFor(model => model.Link, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.Link, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Link, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SourceType, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.SourceType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SourceType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comments, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6" style="color:black;">
#Html.TextAreaFor(model => model.Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SourceDate, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6" style="color:black;">
#Html.EditorFor(model => model.SourceDate, new { htmlAttributes = new { #class = "form-control datepicker datefield" } })
#Html.ValidationMessageFor(model => model.SourceDate, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-med btn-orange" data-dismiss="modal">Cancel</button>
<input class="btn btn-med btn-orange" type="submit" name="submit" value="Add" />
</div>
}
ajax:
$('form', dialog).submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
async: true,
data: $(this).serialize(),
contentType:this.enctype,
success: function (result) {
if (result) {
alert(result)
//Refresh
} else {
alert(result)
}
}
});
return false;
});
I hope to get good working solution for this:
thanks in advance for your time.
Thanks
Ive been using this block of code to solve this problem and ModelState.IsValid in partials for about a year. cheers.
$(function () {
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
$('#modal').on('shown.bs.modal', function () {
$.validator.unobtrusive.parse($(this));
});
$('#modal').on('hidden.bs.modal', function () {
$('#spinner').remove();
});
$.ajaxSetup({ cache: false });
});

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: