I have been trying to come up with a solution for quite some time now but they all seem to fail.
I have two tables -> AssignedRoles & Incidence. Within the "Assignedroles" there is a "Status" Column that is auto-assigned "A" upon creation of data.
Given the nature of my program, i would like to change this value from "A" to "C" but from the "Incidence" Controller on the Edit Method.
Below is what i have tried.
public async Task<ActionResult> Edit(Incidence incidence, AssignedRoles assignedRoles)
{
if (ModelState.IsValid)
{
assignedRoles.Status = "C";
DB.Entry(incidence).State = EntityState.Modified;
DB.AssignedRoles.Add(assignedRoles);
UpdateModel(assignedRoles);
await DB.SaveChangesAsync();
return RedirectToAction("Dashboard");
}
return View(incidence);
}
The View Controller below displays Incidences allocated to the specific admin
The Members() contains the View from LoadUsersData()
public ActionResult Members()
{
return View();
}
public ActionResult LoadUsersData()
{
try
{
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
var adminUserID = Convert.ToInt32(Session["AdminUser"]);
var rolesData = _IUsers.ShowallUsersUnderAdmin(sortColumn, sortColumnDir, searchValue, adminUserID);
recordsTotal = rolesData.Count();
var data = rolesData.Skip(skip).Take(pageSize).ToList();
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal, data = data });
}
catch (Exception)
{
throw;
}
}
The Edit Controller
[HttpGet]
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Incidence incidence = await DB.Incidences.FindAsync(id);
if (incidence == null)
{
return HttpNotFound();
}
return View(incidence);
}
Incidence Model
public class Incidence
{
[Key]
public int RegistrationID { get; set; }
[Required]
public string Name { get; set; }
[Required]
[MaxLength(7)]
public string TSCNO { get; set; }
public string General { get; set; }
public string Location { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
public string Cell { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[DataType(DataType.MultilineText)]
public string Issue { get; set; }
public int? RoleID { get; set; }
[DataType(DataType.MultilineText)]
[MinLength(5,ErrorMessage ="Provide Valid Feedback")]
public string FeedBack { get; set; }
}
AssignedRoles Model
public class AssignedRoles
{
[Key]
public int AssignedRolesID { get; set; }
public int? AssignToAdmin { get; set; }
public int? CreatedBy { get; set; }
public DateTime? CreatedOn { get; set; }
public int RegistrationID { get; set; }
public string Status { get; set; }
}
Incidence Edit View
#model CallCentre.Models.Incidence
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/AdminLTE.cshtml";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.RegistrationID)
<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">
#Html.LabelFor(model => model.TSCNO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TSCNO, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TSCNO, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.General, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.General, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.General, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Location, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Location, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Location, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Cell, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Cell, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Cell, "", 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.Issue, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Issue, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Issue, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FeedBack, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FeedBack, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FeedBack, "", 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>
Modify your edit action to the code below.
// remove assignedRoles object on the parameter, we only need incidence
public async Task<ActionResult> Edit(Incidence incidence)
{
if (ModelState.IsValid)
{
// we need to select the assignedRole from that RegistrationId
var role = db.AssignedRoles.FirstOrDefault(a=>a.RegistrationID == incidence.RegistrationID)
role.Status = "C";
DB.Entry(incidence).State = EntityState.Modified;
// you're just editing the assignedRole right? no need to add a new one. Comment out or remove the code below
// DB.AssignedRoles.Add(assignedRoles);
// UpdateModel(assignedRoles);
await DB.SaveChangesAsync();
return RedirectToAction("Dashboard");
}
return View(incidence);
}
Related
I am trying to create a golf score app. I have created the database that has the following tables Round, Course and Hole.
The hole table has a foreign key to the courseId as when I create each hole I want to link it to a course.
When clicking on the create new I would like to have a dropdown list to select the courseId from when inputting all the hole details.
But when I click on the create new I get the following error in the Hole view model.
System.ArguementNullException: Value can not be Null. Parameter name items. in my Create action code within the HoleViewModelController.
This is my HoleViewModel code
public class HoleViewModel
{
[Key]
public int HoleId { get; set; }
public int HoleNumber { get; set; }
public int Par { get; set; }
public int Length { get; set; }
public int StrokeIndex { get; set; }
[ForeignKey("Course")]
public int? CourseId { get; set; }
public IEnumerable<SelectListItem> CourseNamesDropdownList { get; set; }
public virtual CourseViewModel Course { get; set; }
}
}
This is my CourseViewModel code
public class CourseViewModel
{
[Key]
public int CourseId { get; set; }
public string CourseName { get; set; }
This is my HoleViewModelController Create action
public ActionResult Create()
{
ViewBag.CourseId = new SelectList(db.CourseViewModels, "CourseId", "CourseName");
return View();
}
This is my MVC Create view
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>HoleViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.HoleNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HoleNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HoleNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Par, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Par, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Par, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Length, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Length, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Length, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StrokeIndex, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StrokeIndex, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StrokeIndex, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CourseId, "CourseId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Course.CourseId, Model.CourseNamesDropdownList, "Please select from List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CourseId, "", 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>
Ok so i resolved this issue by ammending the ActionResult Create code from
public ActionResult Create()
{
ViewBag.CourseId = new SelectList(db.CourseViewModels, "CourseId", "CourseName");
return View();
}
To
public ActionResult Create()
{
var dbcourse = db.Course.ToList();
//Make selectlist, which is IEnumerable<SelectListItem>
var courseNameDropdownList = new SelectList(db.Course.Select(item => new SelectListItem()
{
Text = item.CourseName.ToString(),
Value = item.CourseId.ToString()
}).ToList(), "Value", "Text");
// Assign the Selectlist to the View Model
var viewCourse = new HoleViewModel()
{
Course = dbcourse.FirstOrDefault(),
// The Dropdownlist values
CourseNamesDropdownList = courseNameDropdownList,
};
//ViewBag.CourseId = new SelectList(db.CourseViewModels, "CourseId", "CourseName");
return View(viewCourse);
}
This has allowed the dropdown to be populated and be added to the view.
I'm working on an application that relies on an existing SQL Server database. I have created the Model, the Controller and a Create View using the Entity Frameworks code-first approach in Visual Studio. At the moment the code works for all fields and accepts null for the fields that should contain the path to external files (not in the DB).
The Model:
namespace Centurion.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Fontane")]
public partial class Fontane
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Fontane()
{
Interventi = new HashSet<Interventi>();
}
[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int FontanaID { get; set; }
private string _CodificaSIMU;
[StringLength(20)]
public string CodificaSIMU
{
get
{
if (string.IsNullOrEmpty(_CodificaSIMU))
{
return _CodificaSIMU;
}
return _CodificaSIMU.ToUpper();
}
set
{
_CodificaSIMU = value;
}
}
//public string CodificaSIMU { get; set; }
[Required]
[StringLength(255)]
public string Nome { get; set; }
[StringLength(255)]
public string Indirizzo { get; set; }
public int? Municipio { get; set; }
[Required]
public double Latitudine { get; set; }
[Required]
public double Longitudine { get; set; }
[Required]
public int TipoFontana { get; set; }
[Required]
public int TipoImpianto { get; set; }
[Required]
public int Frequenza { get; set; }
[Required]
public bool Svuotamento { get; set; }
public bool? Active { get; set; }
public bool? Allarme { get; set; }
[StringLength(255)]
public string Foto { get; set; }
[StringLength(255)]
public string Allegato1 { get; set; }
[StringLength(255)]
public string Allegato2 { get; set; }
public string Note { get; set; }
[Required]
public int UserIDCrea { get; set; }
[Required]
public DateTime DataCrea { get; set; }
[Required]
public int UserIDModifica { get; set; }
[Required]
public DateTime DataModifica { get; set; }
public virtual Municipi Municipi { get; set; }
public virtual TipiFontana TipiFontana { get; set; }
public virtual Impianto Impianto { get; set; }
public virtual Utenti Utenti { get; set; }
public virtual Utenti Utenti1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Interventi> Interventi { get; set; }
}
public class FontaneFiles
{
[DataType(DataType.Upload)]
[Display(Name = "Upload Foto")]
public string FotoFile { get; set; }
[DataType(DataType.Upload)]
[Display(Name = "Upload Allegato1")]
public string All1File { get; set; }
[DataType(DataType.Upload)]
[Display(Name = "Upload Allegato2")]
public string All2File { get; set; }
}
}
As you can see I have added a second class for uploading the files since the relative table in the DB has just a string for the path in the server.
This is the code of my controller which works fine except the file upload part:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Crea([Bind(Include = "FontanaID,CodificaSIMU,Nome,Indirizzo,Municipio,Latitudine,Longitudine,TipoFontana,TipoImpianto,Frequenza,Svuotamento,Foto,Allegato1,Allegato2,Note")] Fontane fontane)
//public ActionResult Crea([Bind(Include = "FontanaID,CodificaSIMU,Nome,Indirizzo,Municipio,Latitudine,Longitudine,TipoFontana,TipoImpianto,Frequenza,Svuotamento,Active,Allarme,Foto,Allegato1,Allegato2,Note,UserIDCrea,DataCrea,UserIDModifica,DataModifica")] Fontane fontane)
{
// to be replaced in production mode with logged user
fontane.UserIDCrea = cUser;
fontane.UserIDModifica = cUser;
// set date as NOW
fontane.DataCrea = DateTime.Now;
fontane.DataModifica = DateTime.Now;
// no allarm when creating
fontane.Allarme = false;
// active when creating
fontane.Active = true;
fontane.Latitudine = Convert.ToDouble(fontane.Latitudine);
fontane.Longitudine = Convert.ToDouble(fontane.Longitudine);
if (ModelState.IsValid)
{
try
{
db.Fontane.Add(fontane);
db.SaveChanges();
return RedirectToAction("Indice");
}
catch (DbUpdateException)
{
ModelState.AddModelError(string.Empty, "Fontana esistente!");
}
catch (Exception ex)
{
return View("Error", new HandleErrorInfo(ex, "Fontane", "Crea"));
}
return View();
}
ViewBag.TipoImpianto = new SelectList(db.Impianto, "ImpiantoID", "Impianto1", fontane.TipoImpianto);
ViewBag.Municipio = new SelectList(db.Municipi, "MunicipioID", "Municipio", fontane.Municipio);
ViewBag.TipoFontana = new SelectList(db.TipiFontana, "TipoID", "Descrizione", fontane.TipoFontana);
ViewBag.UserIDCrea = new SelectList(db.Utenti, "UserID", "UserName", fontane.UserIDCrea);
ViewBag.UserIDModifica = new SelectList(db.Utenti, "UserID", "UserName", fontane.UserIDModifica);
return View(fontane);
}
The View:
#model Centurion.Models.Fontane
#{
ViewBag.Title = "Crea";
}
<h2>Aggiungi Fontana</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CodificaSIMU, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CodificaSIMU, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CodificaSIMU, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Nome, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Nome, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Nome, "", new { #class = "text-danger" })
</div>
</div>
<fieldset>
<legend>Ubicazione</legend>
<div class="form-group">
#Html.LabelFor(model => model.Indirizzo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Indirizzo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Indirizzo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Municipio, "Municipio", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Municipio", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Municipio, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Latitudine, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Latitudine, new
{
htmlAttributes = new
{
placeholder = "Latitudine = 41,..... (con la virgola)",
#class = "form-control"
}
})
#Html.ValidationMessageFor(model => model.Latitudine, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Longitudine, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Longitudine, new
{
htmlAttributes = new
{
placeholder = "Longitudine = 12,..... (con la virgola)",
#class = "form-control"
}
})
#Html.ValidationMessageFor(model => model.Longitudine, "", new { #class = "text-danger" })
</div>
</div>
</fieldset>
<div class="form-group">
#Html.LabelFor(model => model.TipoFontana, "TipoFontana", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("TipoFontana", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TipoFontana, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TipoImpianto, "TipoImpianto", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("TipoImpianto", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TipoImpianto, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Frequenza, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Frequenza, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Frequenza, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Svuotamento, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Svuotamento)
#Html.ValidationMessageFor(model => model.Svuotamento, "", new { #class = "text-danger" })
</div>
</div>
</div>
#Html.HiddenFor(m => m.Active)
#Html.HiddenFor(m => m.Allarme)
<div class="form-group">
#Html.LabelFor(model => model.Foto, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Foto, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Foto, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Allegato1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Allegato1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Allegato1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Allegato2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Allegato2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Allegato2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Note, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Note, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Note, "", new { #class = "text-danger" })
</div>
</div>
#Html.HiddenFor(m => m.UserIDCrea)
#Html.HiddenFor(m => m.DataCrea)
#Html.HiddenFor(m => m.UserIDModifica)
#Html.HiddenFor(m => m.DataModifica)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Crea" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Elenco Fontane", "Indice")
</div>
I can't change the DB table but I need to find a way to trigger the upload of an image and other files (should be pdf or Excel). Files will be stored in the subfolders of the app_data folder.
If I add the files to the same class of Fontane, I get a table error. I tried to combine the two classes with a tuple but I don't have any idea how to manage them in the Controller. Any help will be apreciated.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Net I was trying to do a Edit for uploading a image but now whenever I edit it crashes and gives 'System.ArgumentNullException' occurred in System.Core.dll but was not handled in user code'. This all started when I tried to implement an edit for the image upload. It crashes on the edit.cshtml page, I have placed a comment right where it crashes. Any help would be really appreciated, if you require any more information please let me know
AnimalsController
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "LatinNameID,CommonNameID,LatinName,CommonName,GenusID,SpeciesID,Description,FamilyID,CountryID,ContinentID,OrderID")] Animal animal, HttpPostedFileBase upload,string latinID,string commonID)
{
var animalToUpdate = db.Animals.Find(latinID,commonID);
//Does a check to see if entry exists in database
if ((db.Animals.Any(ac => ac.LatinName.Equals(animal.LatinName))) || (db.Animals.Any(ac => ac.CommonName.Equals(animal.CommonName))))
{
ModelState.AddModelError("LatinName", "Already Exists");
ModelState.AddModelError("CommonName", "Duplicate Entry");
}
else
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
if (animalToUpdate.Files.Any(f => f.FileType == FileType.Avatar))
{
db.File.Remove(animalToUpdate.Files.First(f => f.FileType == FileType.Avatar));
}
var avatar = new File
{
FileName = System.IO.Path.GetFileName(upload.FileName),
FileType = FileType.Avatar,
ContentType = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
avatar.Content = reader.ReadBytes(upload.ContentLength);
}
animalToUpdate.Files = new List<File> { avatar };
}
db.Entry(animal).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
ViewBag.ContinentID = new SelectList(db.Continents, "ContinentID", "ContinentName", animal.ContinentID);
ViewBag.CountryID = new SelectList(db.Countries, "CountryID", "CountryName", animal.CountryID);
ViewBag.FamilyID = new SelectList(db.Families, "FamilyID", "FamilyName", animal.FamilyID);
ViewBag.GenusID = new SelectList(db.Genus, "GenusID", "GenusName", animal.GenusID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderName", animal.OrderID);
ViewBag.SpeciesID = new SelectList(db.Species, "SpeciesID", "SpeciesName", animal.SpeciesID);
return View(animal);
}
Edit View
<h2>Edit</h2>
#using (Html.BeginForm("Edit", "Animals", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Animal</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.LatinNameID)
#Html.HiddenFor(model => model.CommonNameID)
<div class="form-group">
#Html.LabelFor(model => model.LatinName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LatinName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LatinName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CommonName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CommonName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CommonName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GenusID, "GenusID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("GenusID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.GenusID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SpeciesID, "SpeciesID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("SpeciesID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SpeciesID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FamilyID, "FamilyID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("FamilyID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.FamilyID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CountryID, "CountryID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CountryID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContinentID, "ContinentID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ContinentID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ContinentID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderID, "OrderID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("OrderID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.OrderID, "", new { #class = "text-danger" })
</div>
</div>
//Crashes here
#if (Model.Files.Any(f => f.FileType == FileType.Avatar))
{
<div class="form-group">
<span class="control-label col-md-2"><strong>Current Avatar</strong></span>
<div class="col-md-10">
<img src="~/File?id=#Model.Files.First(f => f.FileType == FileType.Avatar).FileId" alt="avatar" />
</div>
</div>
}
<div class="form-group">
#Html.Label("Avatar", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="Avatar" name="upload" />
</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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Model
//Animal
public class Animal
{
[Key, Column(Order = 0)]
public string LatinNameID { get; set; }
public string LatinName { get; set; }
[Key, Column(Order = 1)]
public string CommonNameID { get; set; }
public string CommonName { get; set; }
public string GenusID { get; set; }
public string SpeciesID { get; set; }
public string Description { get; set; }
public string FamilyID { get; set; }
public string CountryID { get; set; }
public string ContinentID { get; set; }
public string OrderID { get; set; }
public virtual Continent Continent { get; set; }
public virtual Genus Genus { get; set; }
public virtual Species Species { get; set; }
public virtual Family Family { get; set; }
public virtual Country Country { get; set; }
public virtual Order Order { get; set; }
public virtual ICollection<File> Files { get; set; }
}
//File
public class File
{
public int FileId { get; set; }
[StringLength(255)]
public string FileName { get; set; }
[StringLength(100)]
public string ContentType { get; set; }
public byte[] Content { get; set; }
public FileType FileType { get; set; }
public string LatinNameID { get; set; }
public string CommonNameID { get; set; }
public virtual Animal Animal { get; set; }
}
The error that you are getting suggests that you are calling a method with a null argument somewhere in your code. Since it crashes with the if statement beginning with Model.Files.Any(f => f.FileType == FileType.Avatar), I would verify that Model.Files is not null before proceeding.
The code could look like the following:
#if (Model.Files != null && Model.Files.Any(f => f.FileType == FileType.Avatar))
{
<div class="form-group">
<span class="control-label col-md-2"><strong>Current Avatar</strong></span>
<div class="col-md-10">
<img src="~/File?id=#Model.Files.First(f => f.FileType == FileType.Avatar).FileId" alt="avatar" />
</div>
</div>
}
If Model.Files should never be null, then you might need to investigate why that value is not being set as well.
I want to make a DropDownList with a numeric rating from 1-5. I have a rating model and I want to apply these dropdown values to WaitTime, Attentive and Outcome.
Can I just set these values in the view and use the model? If so how would i go about doing this?
My Model Class:
public class Ratings
{
//Rating Id (PK)
public int Id { get; set; }
public string UserId { get; set; }
//Medical Practice (FK)
public int MpId { get; set; }
public MP MP { get; set; }
//User ratings (non-key values)
[Required] //Adding Validation Rule
public int WaitTime { get; set; }
[Required] //Adding Validation Rule
public int Attentive { get; set; }
[Required] //Adding Validation Rule
public int Outcome { get; set; }
}
My View:
<div class="form-group">
#Html.LabelFor(model => model.WaitTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.WaitTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.WaitTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Attentive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Attentive, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Attentive, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Outcome, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Outcome, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Outcome, "", new { #class = "text-danger" })
</div>
</div>
Use this instead of EditorFor for each field:
#Html.DropDownListFor(model => model.Outcome, new SelectList(Enumerable.Range(1, 5)))
Here is the working fiddle - https://dotnetfiddle.net/daB2DI
In short, lets say your model is -
public class SampleViewModel
{
[Required] //Adding Validation Rule
public int WaitTime { get; set; }
[Required] //Adding Validation Rule
public int Attentive { get; set; }
[Required] //Adding Validation Rule
public int Outcome { get; set; }
}
And your controller actions are -
[HttpGet]
public ActionResult Index()
{
return View(new SampleViewModel());
}
[HttpPost]
public JsonResult PostData(SampleViewModel model)
{
return Json(model);
}
Your Get CSHTML should be -
#model HelloWorldMvcApp.SampleViewModel
#{
ViewBag.Title = "GetData";
}
<h2>GetData</h2>
#{
var items = new List<SelectListItem>();
for (int i = 1; i < 6; i++)
{
var selectlistItem = new SelectListItem();
var code = 0;
selectlistItem.Text = (code + i).ToString();
selectlistItem.Value = (code + i).ToString();
items.Add(selectlistItem);
}
}
#using (Html.BeginForm("PostData","Home"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SampleViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.WaitTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.WaitTime, items, "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.WaitTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Attentive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Attentive, items, "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Attentive, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Outcome, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Outcome, items, "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Outcome, "", 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>
}
When you run the code, you should see page like below -
And when you select some values and click on create, you should get those values in PostData action.
try to adapt this to your project
in your controller:
ViewBag.ParentID = new SelectList(departmentsQuery, "NewsMID", "Title", selectedDepartment);
return View(model);
in your view put this
#Html.DropDownList("ParentID")
Hey guys i need your help, i have a create employee form in MVC. I fill the form and select from the dropdown list and when i click submit, every other field returns a value except for the dropdown. i can't seem to fix the problem. this is what the form looks like.
this is the CreateEmployee Model
public class CreateEmployee
{
public int Id { get; set; }
public string FullName { get; set; }
[Required]
public string Notes { get; set; }
public int Department { get; set; }
public IEnumerable<AngTestDepartment> Departments { get; set; }
public bool PerkCar { get; set; }
public bool PerkStock { get; set; }
public bool PerkSixWeeks { get; set; }
public string PayrollType { get; set; }
}
the action controller
public ActionResult Employee(){
using (var db = new DepartmentDbContext())
{
var model = new CreateEmployee();
model.Departments = db.AngTestDepartments.ToList();
return View(model);
} }
and the view
#using (Html.BeginForm("CreateEmployee", "Employee", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.FullName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FullName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FullName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Notes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Notes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Notes, "", new { #class = "text-danger" })
</div>
</div>
// the drop down doesnt return a value on submit
<div class="form-group">
#Html.LabelFor(model => model.Department, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Departments,
Model.Departments.Select(d => new SelectListItem()
{
Value = d.id.ToString(),
Text = d.Department
}
), new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Department, "", new { #class = "text-danger" })
</div>
</div> }
and the action result called on submit
public ActionResult CreateEmployee(CreateEmployee newEmployee)
{
DbEmployeeTable.DbEmployeeTable_EmployeeTable(newEmployee);
return RedirectToAction("Employees");
}
thank you very much for your help.
Change the dropdownlist code to:
#Html.DropDownListFor(m => m.Department, new SelectList(Model.Departments.Select(d => new SelectListItem()
{
Value = d.id.ToString(),
Text = d.Department
}
)), new { htmlAttributes = new { #class = "form-control" } })
Dropdownlistfor's first argument should be the value that you're trying to get, and having the second be a select list will save you persistence-related headaches later.
As an aside, I'd also make the Model.Departments.Select result a model property so you don't clutter your view so much, but that's just a style concern.
Instead of
#Html.DropDownListFor(m => m.Departments,
try this...
#Html.DropDownListFor(m => m.Department,
That should return the department Id as an int from the selected value.