I have 2 Separate Tables Products and Product Photo
When I examine any details in the products table, I want the pictures of that product to come. In that case, I pull it into the Detail table in a field called _UrunFotoPartitialView as # html.partitial ("") but always
The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Urun_C7B3883A1159F8EE0177C29B1CA535182B157B3C5BB798ABCC8C2A72FB5CFED9', but this dictionary requires a model item of type 'Tututuncu.Models.UrunFotoViewModel'.
gives an error. How many days I have been dealing but I couldn't do it.
Ürün Class
public partial class Urun
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Urun()
{
this.Firma = new HashSet<Firma>();
this.Musteri = new HashSet<Musteri>();
this.Satis = new HashSet<Satis>();
}
public int UrunID { get; set; }
public Nullable<int> UrunFotoID { get; set; }
public Nullable<int> MarkaID { get; set; }
public string UrunAdi { get; set; }
public Nullable<decimal> UrunFiyat { get; set; }
public Nullable<decimal> UrunAlisFiyat { get; set; }
public Nullable<int> UrunStok { get; set; }
public string UrunAciklama { get; set; }
public Nullable<System.DateTime> UretimYili { get; set; }
public Nullable<System.DateTime> EklenmeTarihi { get; set; }
public Nullable<System.DateTime> GuncellenmeTarihi { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Firma> Firma { get; set; }
public virtual Markalar Markalar { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Musteri> Musteri { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Satis> Satis { get; set; }
public virtual UrunFoto UrunFoto { get; set; }
}
Ürün Foto Class
public partial class UrunFoto
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public UrunFoto()
{
this.Urun = new HashSet<Urun>();
}
public int FotoID { get; set; }
public Nullable<int> UrunFotoID { get; set; }
public string BuyukYol { get; set; }
public string OrtaYol { get; set; }
public string KucukYol { get; set; }
public Nullable<bool> Varsayilan { get; set; }
public string SiraNo { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Urun> Urun { get; set; }
}
My UrunController
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Tututuncu.Models;
namespace Tututuncu.Areas.Yonetim.Controllers
{
[Authorize]
public class UrunController : Controller
{
private StokDBEntities db = new StokDBEntities();
// GET: Yonetim/Urun
public ActionResult Index()
{
return RedirectToAction("Listele");
}
public ActionResult Listele()
{
var urun = db.Urun.Include(u => u.Markalar).Include(u => u.UrunFoto);
return View(urun.ToList());
}
public ActionResult Yeni()
{
ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd");
ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Yeni([Bind(Include = "UrunID,UrunFotoID,MarkaID,UrunAdi,UrunFiyat,UrunAlisFiyat,UrunStok,UrunAciklama,UretimYili,EklenmeTarihi,GuncellenmeTarihi")] Urun urun)
{
if (ModelState.IsValid)
{
db.Urun.Add(urun);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd", urun.MarkaID);
ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol", urun.UrunFotoID);
return View(urun);
}
public ActionResult Guncelle(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Urun urun = db.Urun.Find(id);
if (urun == null)
{
return HttpNotFound();
}
ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd", urun.MarkaID);
ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol", urun.UrunFotoID);
return View(urun);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Guncelle([Bind(Include = "UrunID,UrunFotoID,MarkaID,UrunAdi,UrunFiyat,UrunAlisFiyat,UrunStok,UrunAciklama,UretimYili,EklenmeTarihi,GuncellenmeTarihi")] Urun urun)
{
if (ModelState.IsValid)
{
db.Entry(urun).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd", urun.MarkaID);
ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol", urun.UrunFotoID);
return View(urun);
}
public ActionResult Sil(int id)
{
var silinecekUrun = db.Urun.Find(id);
if (silinecekUrun == null)
return HttpNotFound();
db.Urun.Remove(silinecekUrun);
db.SaveChanges();
return RedirectToAction("Index", "Urun");
}
public ActionResult UrunResimEkle(int id)
{
Urun urun = db.Urun.Find(id);
ViewBag.Foto = urun;
return View(urun);
}
public ActionResult FotoListele(int id)
{
Urun urun = db.Urun.Find(id);
ViewBag.Foto = urun;
return View(urun);
}
[HttpPost]
public ActionResult UrunResimEkle(int uId, HttpPostedFileBase fileUpload)
{
if (fileUpload != null)
{
Image img = Image.FromStream(fileUpload.InputStream);
Bitmap kucukResim = new Bitmap(img, ResimAyar.UrunKucukBoyut);
Bitmap ortaResim = new Bitmap(img, ResimAyar.UrunOrtaBoyut);
Bitmap buyukResim = new Bitmap(img, ResimAyar.UrunBuyukBoyut);
string buyukYol = "/images/UrunFoto/Buyuk/" + Guid.NewGuid() + VirtualPathUtility.GetExtension(fileUpload.FileName);
string ortaYol = "/images/UrunFoto/Orta/" + Guid.NewGuid() + VirtualPathUtility.GetExtension(fileUpload.FileName);
string kucukYol = "/images/UrunFoto/Kucuk/" + Guid.NewGuid() + VirtualPathUtility.GetExtension(fileUpload.FileName);
kucukResim.Save(Server.MapPath(kucukYol));
ortaResim.Save(Server.MapPath(ortaYol));
buyukResim.Save(Server.MapPath(buyukYol));
UrunFoto rsm = new UrunFoto();
rsm.BuyukYol = buyukYol;
rsm.OrtaYol = ortaYol;
rsm.KucukYol = kucukYol;
rsm.UrunFotoID = uId;
if (db.UrunFoto.FirstOrDefault(x => x.UrunFotoID == uId && x.Varsayilan == false) != null)
rsm.Varsayilan = true;
else
rsm.Varsayilan = false;
db.UrunFoto.Add(rsm);
db.SaveChanges();
return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());
}
return View(uId);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Urun View Page
#model IEnumerable<Tututuncu.Models.Urun>
#{
ViewBag.Title = "Ürüne Resim Ekle";
Layout = "~/Areas/Yonetim/Views/Shared/_Layout.cshtml";
}
<!-- Page Content -->
<div id="page-wrapper">
<div class="container-fluid">
<div class="row bg-title">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-12">
<h4 class="page-title">File Upload</h4>
</div>
<div class="col-lg-9 col-sm-8 col-md-8 col-xs-12">
<ol class="breadcrumb">
<li>Yönetim Paneli</li>
<li class="active">File Upload</li>
</ol>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- .row -->
<div class="row">
<div class="col-sm-12 ol-md-6 col-xs-12">
<div class="white-box">
<h3 class="box-title">File Upload1</h3>
<label for="input-file-now">Your so fresh input file — Default version</label>
<form action="/Yonetim/Urun/UrunResimEkle" method="post" enctype="multipart/form-data">
<input type="hidden" name="uId" value="#Model" />
<input type="file" name="fileUpload" />
<input type="submit" name="name" value="Kaydet" class="btn btn-primary" />
</form>
</div>
</div>
</div>
#Html.Partial("FotoListele")
</div>
</div>
My Partitial View Page
#model IEnumerable<Tututuncu.Models.UrunFoto>
#{
ViewBag.Title = "FotoListele";
Layout = "~/Areas/Yonetim/Views/Shared/_Layout.cshtml";
}
<h2>FotoListele</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.BuyukYol)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.BuyukYol)
</td>
</tr>
}
</table>
You have two model types.
Parent: #model IEnumerable<Tututuncu.Models.Urun>
Partial: #model IEnumerable<Tututuncu.Models.UrunFoto>
You're calling Partial using #Html.Partial("FotoListele")
You can use #Html.Partial("FotoListele", THE-NEW-MODEL-OF-LIST-UrunFoto)
When using Partial without passing the new model, it uses the parent model. Thus, it gets exception when trying to perform the casting.
You can either create a new Model that fits the Partial needs, or accept the parent model.
Note: partial class doesn't relate at all to razor engine Html.Partial. more on that Here
Related
I have a Model which i want to edit (Location).This model has a field called ActivityId.I am sending an array of ActivityId-s via ViewData to the view and transform them to a SelectList.
I want the ActivityId field (long) of the Location to be set with the selected item from the dropdownlist (string) - i need a conversion done somehow from string to long before entering the Post Action of the controller.(EditConfirmed)
Models:
[Table("location")]
public partial class Location
{
public Location()
{
StoryLocation = new HashSet<StoryLocation>();
UserStoryLocation = new HashSet<UserStoryLocation>();
}
[Column("id", TypeName = "bigint(20)")]
public long Id { get; set; }
[Column("description")]
[StringLength(255)]
public string Description { get; set; }
[Column("name")]
[StringLength(255)]
public string Name { get; set; }
[Column("activity_id", TypeName = "bigint(20)")]
public long? ActivityId { get; set; }
[ForeignKey("ActivityId")]
[InverseProperty("Location")]
public Activity Activity { get; set; }
}
}
[Table("activity")]
public partial class Activity
{
public Activity()
{
Location = new HashSet<Location>();
}
[Column("activity_id", TypeName = "bigint(20)")]
public long ActivityId { get; set; }
[Column("description")]
[StringLength(255)]
public string Description { get; set; }
[Column("name")]
[StringLength(255)]
public string Name { get; set; }
[Column("type")]
[StringLength(255)]
public string Type { get; set; }
[InverseProperty("Activity")]
public ICollection<Location> Location { get; set; }
}
Controller:
[HttpGet]
public IActionResult Edit(long id = 0)
{
Location loc = this.context.Locations.Find(id);
if (loc == null)
{
return NotFound();
}
ViewData[Constants.ViewData.TActivities]=this.context.Activities
.Select(elem=>
new SelectListItem
{
Text=elem.Name,
Value=elem.ActivityId.ToString()
}
).ToList();
return View(loc);
}
View
#using AdminMVC.Models
#using AdminMVC.ConfigConstants
#using Newtonsoft.Json
#model AdminMVC.Models.Location
#{
List<SelectListItem> dropActivities=ViewData[Constants.ViewData.TActivities] as List<SelectListItem>;
}
<html>
<head>
</head>
<body>
<div id="form">
</div>
<div id="page">
#using (Html.BeginForm("Edit","Location",FormMethod.Post))
{
<div id="table">
<label>Set Location:</label>
<table border="">
#Html.DisplayFor(x=>x.Id)
<tr>
<td>#Html.DisplayNameFor(x=>x.Name)</td>
<td>#Html.EditorFor(x=>x.Name)</td>
</tr>
<tr>
<td>#Html.DisplayNameFor(x=>x.Description)</td>
<td>#Html.EditorFor(x=>x.Description)</td>
</tr>
<div>
<label >Select Activity:</label>
#Html.DropDownList("Activity",dropActivities) //i need to somehow convert the selected value from the dropdown to long before the form is sent to the controller
</div>
</table>
</div>
<div id="control-panel">
<input type="submit" value="Edit">
</div>
}
</body>
</div>
</html>
Post to Controller
[HttpPost, ActionName("Edit")]
public IActionResult EditConfirmed(Location editLoc)
{
if (ModelState.IsValid)
{
this.context.Entry(editLoc).State = EntityState.Modified;
this.context.SaveChanges();
return RedirectToAction("Index");
}
return View(editLoc);
}
P.S:So far the ActivityId of the Location sent to the Post Action is null.I need it to be long.
I solved this problem using the ViewData component.I would first serialize the SelectList using NewtonSoft then i would add it to the ViewData dictionary.When rendering the view i would use the DropDownList razor Html Helper method.
Model
public class FixedLocation
{
[Column("id", TypeName = "bigint(20)")]
public long Id { get; set; }
[Column("coords")]
[StringLength(255)]
public string Coords { get; set; }
[Column("name")]
[StringLength(255)]
[Required]
public string Name { get; set; }
[Column("google_id")]
[StringLength(255)]
[Required]
public string GoogleId { get; set; }
}
Extension method for getting a List of SelectListItem
public static IEnumerable<SelectListItem> ToSelectList<T,Tkey,Tvalue>(
this IQueryable<T> myenum,
Func<T,(Tkey,Tvalue)>kvpair)
{
return myenum.Select(elem=>kvpair(elem))
.Select(tuple=>new SelectListItem{
Text=tuple.Item1.ToString(),
Value=tuple.Item2.ToString()
});
}
Controller:
public IActionResult Create()
{
Location targetLocation = new Location();
ViewData[Constants.ViewData.TFixedLocations]=
this.context.FixedLocation
.ToSelectList<FixedLocation,string,long>
(elem=>(elem.Name,elem.Id)).ToList();
return View(targetLocation);
}
View:
#using AdminMVC.Models
#model AdminMVC.Models.Location
#using AdminMVC.ConfigConstants
#{
dropFixedLocations=ViewData[Constants.ViewData.TFixedLocations] as List<SelectListItem>;
}
<div>
<label >Select FixedLocation:</label>
#Html.DropDownListFor(x=>Model.Id,dropFixedLocations)
</div>
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I added the code to show many checkboxes from my table (HairTags) and in my form CreationUpload.cshtml i got the following error :
An exception of type 'System.NullReferenceException' occurred in
App_Web eba142hb.dll but was not handled in user code Additional
information: Object reference not set to an instance of an object.
Object reference not set to an instance of an object.
<div class="col-md-12">
#for (int i = 0; i < Model.CreationHairTags.Count; i++)
{
#Html.CheckBoxFor(m => Model.CreationHairTags[i].IsChecked)
#Model.CreationHairTags[i].Text
#Html.HiddenFor(m => Model.CreationHairTags[i].Value)
#Html.HiddenFor(m => Model.CreationHairTags[i].Text)<br />
}
</div>
this is my model Creation.cs (in bold the added code)
namespace HairCollection3.Models
{
public class Creation
{
public string UserId { get; set; }
[Key]
public int CreationId { get; set; }
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
[Display(Name = "Sex", ResourceType = typeof(ViewRes.Names))]
public string CreationSex { get; set; }
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
[Display(Name = "CreationTitle", ResourceType = typeof(ViewRes.NamesCreation))]
[StringLength(2000)]
[AllowHtml]
public string CreationTitle { get; set; }
public string CreationPhotoBis { get; set; }
public string Creationtag { get; set; }
public virtual ICollection<CreationLike> CreationLikes { get; set; }
}
public class CreationLike
{
public int CreationId { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
[Key]
public int CreationLikeId { get; set; }
public virtual Creation ParentCreation { get; set; }
}
public class HairTag
{
[Key]
public int HairTagId { get; set; }
[Required]
public string HairTagTitle { get; set; }
[Required]
public string HairTagType { get; set; }
[Required]
public int HairTagOrder { get; set; }
}
***//CHECKBOXES
public class HairTagModel
{
[Key]
public int Value { get; set; }
public string Text { get; set; }
public bool IsChecked { get; set; }
}
public class HairTagList
{
private ApplicationDbContext creationdb = new ApplicationDbContext();
public HairTagList()
{
var HairTagList = creationdb.HairTags.ToList();
List<HairTagModel> obj = new List<HairTagModel>();
foreach (var tags in HairTagList)
{
obj.Add(new HairTagModel
{
Text = tags.HairTagTitle,
Value = tags.HairTagId,
IsChecked = false
});
}
this.CreationHairTags = obj;
}
public List<HairTagModel> CreationHairTags { get; set; }
//public List<HairTagModel> ListHairTags { get; set; }
}
public class CreationHairTagsModel
{
public Creation Creation { get; set; }
public List<HairTagModel> CreationHairTags { get; set; }
}
}***
My controller CreationController.cs
// GET: /Creation/CreationUpload
[Authorize]
public ActionResult CreationUpload()
{
CreationHairTagsModel creation = new CreationHairTagsModel();
return View(creation);
//return View();
}
// POST: /Creation/CreationUpload
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult CreationUpload([Bind(Include = "CreationId,CreationSex,CreationTitle,CreationPhotoBis,CreationHairTags")] CreationHairTagsModel creation, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
// update each field manually
foreach (var file in files)
{
if (file != null)
{
if (file.ContentLength > 0)
{
....CODE UPLOAD HIDDEN....
//Avoid Script
var CreationTitletocheck = Regex.Replace(creation.Creation.CreationTitle, #"<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>", string.Empty);
CreationTitletocheck = Regex.Replace(CreationTitletocheck, #"(?></?\w+)(?>(?:[^>'""]+|'[^']*'|""[^""]*"")*)>", string.Empty);
creation.Creation.CreationTitle = CreationTitletocheck;
//Tags
StringBuilder sb = new StringBuilder();
foreach (var item in creation.CreationHairTags)
{
if (item.IsChecked)
{
sb.Append(item.Text + ",");
}
}
creation.Creation.Creationtag = sb.ToString();
creation.Creation.UserId = User.Identity.GetUserId();
db.Creations.Add(creation.Creation);
db.SaveChanges();
}
}
}
}
//UserId
return RedirectToAction("CreationList", "Creation", new { UserId = User.Identity.GetUserId() });
}
return View(creation);
}
My page of upload CreationUpload.cshtml
#model HairCollection3.Models.CreationHairTagsModel
#using Microsoft.AspNet.Identity
#{
ViewBag.Title = ViewRes.NamesCreation.CreationUploadTitle;
}
<div class="col-sm-12 col-md-12 chpagetop">
<h1>#ViewRes.Shared.PublishAPhoto</h1>
<hr />
#using (Html.BeginForm("CreationUpload", "Creation", FormMethod.Post, new { id = "CreationUpload", enctype = "multipart/form-data", onsubmit = "$('#creationloading').show(); $('#creationform').hide();" }))
{
#Html.AntiForgeryToken()
<div class="col-md-12" id="creationloading" style="display:none">
<div id="progress">
<p>#ViewRes.Shared.UploadPhotoProgress<strong>0%</strong></p>
<progress value="5" min="0" max="100"><span></span></progress>
</div>
</div>
<div class="col-md-12" id="creationform">
<div class="col-md-12">
#Html.ValidationMessageFor(m => m.Creation.CreationSex)
#Html.RadioButtonFor(m => m.Creation.CreationSex, "F", new { #checked = true }) #ViewRes.Shared.WomanHairstyle #Html.RadioButtonFor(m => m.Creation.CreationSex, "M") #ViewRes.Shared.ManHairstyle
</div>
<div class="col-md-12">
#Html.ValidationMessageFor(m => m.Creation.CreationTitle)
#Html.TextBoxFor(m => m.Creation.CreationTitle, new { #class = "inputplaceholderviolet wid100x100", placeholder = HttpUtility.HtmlDecode(Html.DisplayNameFor(m => m.Creation.CreationTitle).ToHtmlString()), onfocus = "this.placeholder = ''", onblur = "this.placeholder = '" + HttpUtility.HtmlDecode(Html.DisplayNameFor(m => m.Creation.CreationTitle).ToHtmlString()) + "'" })
</div>
<div class="col-md-12">
#for (int i = 0; i < Model.CreationHairTags.Count; i++)
{
#Html.CheckBoxFor(m => Model.CreationHairTags[i].IsChecked)
#Model.CreationHairTags[i].Text
#Html.HiddenFor(m => Model.CreationHairTags[i].Value)
#Html.HiddenFor(m => Model.CreationHairTags[i].Text)<br />
}
</div>
<div class="col-md-12" style="text-align: center">
<p style="display: inline-block">
<input type="file" accept="image/*" onchange="loadFile(event)" name="files" id="file1" translate="yes" data-val="true" data-val-required="A File is required." class="wid100x100" /><label for="file1"></label>
<img id="output" style="max-width:200px;"/>
</p>
</div>
<div class="col-sm-12 col-md-12 chpagetopdiv">
<button type="submit" title="#ViewRes.Shared.Publish"><span class="glyphicon glyphicon-share-alt"></span> #ViewRes.Shared.Publish</button>
</div>
</div>
}
</div>
What is wrong in my code please help and explain ?
Important: In C#, every collection must be initialized before being accessed
The error occurs when you are trying to access from the View to the collection CreationHairTags, which is not initialized. Replace your model to initialize collection in the class constructor:
public class CreationHairTagsModel
{
public Creation Creation { get; set; }
public List<HairTagModel> CreationHairTags { get; set; }
public CreationHairTagsModel()
{
CreationHairTags = new List<HairTagModel>();
}
}
I am using autogenerated entity model classes and than i used partial class with metadata to put validations on auto genetrated classes like below.
public class tblDepartmentCustom
{
[Key]
public int DepartmentId { get; set; }
[Required(ErrorMessage = "Department name is required")]
public string DepartmentName { get; set; }
}
[MetadataType(typeof(tblDepartmentCustom))]
public partial class tblDepartmentMaster
{
}
The original class that was generated by entity framework is given below.
public partial class tblDepartmentMaster
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public tblDepartmentMaster()
{
this.tblDesignationMasters = new HashSet<tblDesignationMaster>();
}
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<tblDesignationMaster> tblDesignationMasters { get; set; }
}
So the problem here is that whenever i try to validated model state it comes out to be true.below is the code.
#model EmployeeManager.Models.tblDepartmentCustom
#{
ViewBag.Title = "InsertDepartment";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}<div class="col-md-4">
#using (Html.BeginForm("InsertDepartment", "Departments", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<span class="error-class">#ViewBag.FoundError</span>
<br />
<label>Department Name</label>
#Html.TextBoxFor(m => m.DepartmentName, new { #class = "form-control" })
<br />
<input type="submit" class="btn btn-info" value="Add Department" />
}
</div>
And the action below.
[HttpGet]
public ActionResult InsertDepartment()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("InsertDepartment")]
public ActionResult InsertDepartmentPost()
{
using (PMSEntities dc = new PMSEntities())
{
tblDepartmentMaster dm = new tblDepartmentMaster();
TryUpdateModel(dm);
if(ModelState.IsValid)
{
dc.tblDepartmentMasters.Add(dm);
dc.SaveChanges();
return View("_Success");
}
else
{
ViewBag.FoundError = "Department name is required.";
return View();
}
}
}
In order for partial classes to work, both partials must have the same namespace. You don't have to move the actual files around your file structure, just edit the namespace of tblDepartmentCustom to match that of tblDepartmentMaster.
Although this error is very common in the forum, but i am not able to understand how to fix it in my project. I am new to MVC framework.
View code:-
#model ClassifiedProject.Models.CreateAdvertVM
<div class="editor-label">#Html.LabelFor(model => model.AdvTitle) <i>(E.g. Old Samsung Galaxy Tab 2)</i></div>
<div class="editor-field">
#Html.EditorFor(model => model.AdvTitle)
#Html.ValidationMessageFor(model => model.AdvTitle)
</div>
<div class="editor-label">#Html.LabelFor(model => model.AdvDescription)</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.AdvDescription)
#Html.ValidationMessageFor(model => model.AdvDescription)
</div>
<div class="editor-label">#Html.Label("Advertisement Category")</div>
<div class="editor-label">
#Html.DropDownListFor(model => model.SelectedCategoryId, Model.Categories, new { #class = "ddlcs" })
#Html.ValidationMessageFor(model => model.SelectedCategoryId)
</div>
<p><input type="submit" value="Save" /></p>
Controller code of Save button actionresult:-
[HttpPost]
public ActionResult Create(TR_ADVERTISEMENT tr_advert)
{
if (ModelState.IsValid)
{
tr_advert.CreatedDate = tr_advert.ModifiedDate = DateTime.Now;
if (tr_advert.IsPriceOnRequest)
{
tr_advert.CurrencyID = 0;
tr_advert.Price = 0;
}
db.ADVERTISEMENT.Add(tr_advert);
db.SaveChanges();
return RedirectToAction("Index");
}
Controller code for the form in render stage:-
// GET: /Advert/Create
public ActionResult Create()
{
var model = new CreateAdvertVM();
ViewBag.Message = "Post New Advertisement.";
////Render Category DDL
var cat = from s in db.CategoryDbSet
where s.IsActive == true
orderby s.CatName
select new { s.CatID, s.CatName };
var catListItems = cat.ToList().Select(c => new SelectListItem
{
Text = c.CatName,
Value = c.CatID.ToString()
}).ToList();
catListItems.Insert(0, new SelectListItem { Text = "[--Select the category--]", Value = "" });
model.Categories = catListItems;
return View(model);
ViewModel inherited from EF class:-
[NotMapped]
public class CreateAdvertVM : TR_ADVERTISEMENT
{
[DisplayName("Category")]
[Required]
public int? SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
EF Model:-
public class TR_ADVERTISEMENT
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AdvID { get; set; }
[Required]
[DisplayName("Sub Category")]
public int SubCatID { get; set; }
public int CurrencyID { get; set; }
[DisplayName("Price on request")]
public bool IsPriceOnRequest { get; set; }
[DisplayName("Posted Date")]
[DisplayFormat (DataFormatString="{0:dd-MM-yyyy}")]
public Nullable<System.DateTime> CreatedDate { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
}
On the save button click, i have to save the data into the tr_advertisement table using the EF model.
Please suggest the solution to this problem.
It is the model type you are passing into your Create ActionMethod.
public ActionResult Create(TR_ADVERTISEMENT tr_advert)
should be
public ActionResult Create(CreateAdvertVM tr_advert)
I am assuming that if your model is not valid, you are passing it back further down in your action result (which you are not showing), such as
Return View(tr_advert)
But, you are passing the wrong model type at that point for that view.
EDIT
I would also update your view model so that instead of inheriting from the EF class, simply include the EF class as a property.
public class CreateAdvertVM
{
[DisplayName("Category")]
[Required]
public int? SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
public TR_ADVERTISEMENT tr_advert{get;set;}
}
This will make it so that your save code in the Create method can still be used with only minor modifications
[HttpPost]
public ActionResult Create(CreateAdvertVM model)
{
if (ModelState.IsValid)
{
model.tr_advert.CreatedDate = model.tr_advert.ModifiedDate = DateTime.Now;
if (model.tr_advert.IsPriceOnRequest)
{
model.tr_advert.CurrencyID = 0;
model.tr_advert.Price = 0;
}
db.ADVERTISEMENT.Add(model.tr_advert);
db.SaveChanges();
return RedirectToAction("Index");
}
I'm brand new to ASP.net MVC (About a week in), so there is still quite a bit of confusion...
How do I go about passing the current views model into the controller so I can get at the model data?
View
#model KineticBomardment.Models.Blog.BlogPost
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(false)
<fieldset class="block">
<div class="input">
#Html.LabelFor(x => x.Title)
#Html.EditorFor(x => x.Title)
</div>
<div class="input">
#Html.LabelFor(x => x.ShortDescription)
#Html.EditorFor(x => x.ShortDescription)
</div>
<div class="button">
#Html.ActionLink("Submit", "CreateNewBlogEntry", "Admin" );
</div>
</fieldset>
}
I then have a controller of
public ActionResult CreateNewBlogEntry(Models.Blog.BlogPost currentBlogModel)
{
if (ModelState.IsValid)
{
currentBlogModel.CreatePost();
return Content("Created!");
}
return View();
}
And a model of
public class BlogPost
{
public int Id { get; set; }
[Required]
[Display(Name="Title of Blog Post")]
public string Title { get; set; }
public DateTime DateCreated { get; set; }
[Required]
[Display(Name = "Short Description")]
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
public int HeaderImage { get; set; }
public ICollection<BlogPost> GetAllPosts()
{
ICollection<BlogPost> posts = new List<BlogPost>();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["KineticBombardment"].ToString()))
{
using (SqlCommand cmd = new SqlCommand("select title, datecreated, shortdescription from blogentries where id > 0", connection))
{
cmd.Parameters.Clear();
connection.Open();
cmd.ExecuteNonQuery();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
this.ShortDescription = reader["shortdescription"].ToString();
this.Title = reader["title"].ToString();
this.DateCreated = Convert.ToDateTime(reader["datecreated"].ToString());
posts.Add(this);
}
}
return posts;
}
}
}
public void CreatePost()
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["KineticBombardment"].ToString()))
{
using (SqlCommand cmd = new SqlCommand("insert into blogentries (shortdescription, datecreated, blogtype, title) values (#shortdescription, #datecreated, #blogtype, #title)", connection))
{
cmd.Parameters.Clear();
connection.Open();
cmd.Parameters.Add("#shortdescription", SqlDbType.VarChar, 500).Value = this.ShortDescription;
cmd.Parameters.Add("#datecreated", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("#blogtype", SqlDbType.Int).Value = 1;
cmd.Parameters.Add("#title", SqlDbType.VarChar, 255).Value = this.Title;
cmd.ExecuteNonQuery();
}
}
}
}
Change:
<div class="button">
#Html.ActionLink("Submit", "CreateNewBlogEntry", "Admin" );
</div>
To:
<input type="submit" class="button" />
and
public ActionResult CreateNewBlogEntry(Models.Blog.BlogPost currentBlogModel)
{
if (ModelState.IsValid)
{
currentBlogModel.CreatePost();
return Content("Created!");
}
return View();
}
to
public ActionResult CreateNewBlogEntry()
{
return View();
}
[HttpPost]
public ActionResult CreateNewBlogEntry(Models.Blog.BlogPost model)
{
if (ModelState.IsValid)
{
currentBlogModel.CreatePost();
return Content("Created!");
}
return View();
}
I've made some assumptions, but that should work