Passing Model Object Data from View, to Controller, to Model? - asp.net-mvc

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

Related

Asp.NET MVC Product> ProductPhoto

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

how to upload image in ActionResult asp.net mvc?

I want set image to my post but I can't.all model field is fill but image field is null
my model class:
public class Game
{
public Game()
{
Platforms = new List<Platform>();
}
[Key]
public int GameID { get; set; }
public string Name { get; set; }
public string Image { get; set; }
[AllowHtml]
public string Description { get; set; }
public DateTime PublishDate { get; set; }
public virtual ICollection<Platform> Platforms { get; set; }
}
my controller class :
public ActionResult Create_post(Game model,int[] platformsIds)
{
if (ModelState.IsValid)
{
foreach (var pId in platformsIds)
{
var platform = _repository.Get<Platform>(pId);
model.Platforms.Add(platform);
}
_repository.Add<Game>(model);
return RedirectToAction("Index");
}
ViewBag.Platforms = _repository.GetAll<Platform>().ToList();
ViewBag.HtmlContent = model.Description;
return View(model);
}
thank you
you just check image url before save your model
in your view you must have this code
<div class="form-group">
#Html.LabelFor(model => model.Image, htmlAttributes: new { #class = "control-label col-md-1" })
<div class="col-md-4">
<div class="col-md-6 col-md-push-0">
<input type="file" class="form-control" name="ImageUrl" id="ImageUrl" />
</div>
#Html.ValidationMessageFor(model => model.Image, "", new { #class = "text-danger" })
</div>
</div>
in your controller you must change your code
public ActionResult Create_post(Game model,int[] platformsIds,HttpPostedFileBase ImageUrl)
{
if (ModelState.IsValid)
{
foreach (var pId in platformsIds)
{
var platform = _repository.Get<Platform>(pId);
model.Platforms.Add(platform);
}
if (ImageUrl != null && ImageUrl.ContentLength > 0)
{
var uploadDir = "~/images/Games/"; // your location for save images
string image = Guid.NewGuid().ToString() + ImageUrl.FileName;
var imagePath = Path.Combine(Server.MapPath(uploadDir),image);
ImageUrl.SaveAs(imagePath);
model.Image = image;
}
_repository.Add<Game>(model);
return RedirectToAction("Index");
}
ViewBag.Platforms = _repository.GetAll<Platform>().ToList();
ViewBag.HtmlContent = model.Description;
return View(model);
}

Error in my upload page after i changed my model [duplicate]

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>();
}
}

ASP.NET MVC5 - Validate against other table

Using VS2013 and building my first MVC app with EF6 (database first). I have a jobs table and a related items table (there can be millions of records per job). I need to give the user a way to export a subset of items (e.g. item 1,000 - 10,000).
So my controller contains a get method that opens a new view where they can enter the start and end values.
I want to default these to the min and max values from the items table and then I need to validate that the two numbers entered exist in the items table.
Here's my view:
#model PSAMVC.Models.Job
#{
ViewBag.Title = "ExportToLake";
}
<h2>ExportToLake</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Job</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.JobNo, "JobNo", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.JobNo, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.VersionRef, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.VersionRef, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PSAJobRef, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.PSAJobRef, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.Label("Start Seq No", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("StartSeqNo")
</div>
</div>
<div class="form-group">
#Html.Label("End Seq No", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("EndSeqNo")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Export" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
How/where would I enter the code to validate the two numbers against the items table?
I would think that doing in the view is the best place as the user would get immediate feedback and I can code the controller method knowing it will always be passed valid values.
I could add a view to Db that contains the job no and min and max item no, but it seems like a bit of a hack.
TIA
Mark
Update: here's my Jobs model:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PSAMVC.Models
{
using System;
using System.Collections.Generic;
public partial class Job
{
public Job()
{
this.Items = new HashSet<Item>();
this.Reprints = new HashSet<Reprint>();
this.Scans = new HashSet<Scan>();
this.LabelTypes = new HashSet<LabelType>();
}
public int ID { get; set; }
public string JobNo { get; set; }
public string VersionRef { get; set; }
public string PSAJobRef { get; set; }
public int TotalCopies { get; set; }
public int CopiesPerBundle { get; set; }
public int CopiesPerCarton { get; set; }
public int CopiesPerMasterCarton { get; set; }
public Nullable<int> CopiesPerPallet { get; set; }
public int CardType { get; set; }
public string CardTitle { get; set; }
public string CardMMYY { get; set; }
public string StartSerialNo { get; set; }
public int StartBundleNo { get; set; }
public int StartCartonNo { get; set; }
public Nullable<int> StartMasterCartonNo { get; set; }
public Nullable<int> StartPalletNo { get; set; }
public string ProductUPC { get; set; }
public string PackagingUPC { get; set; }
public bool PreProcessed { get; set; }
public bool Completed { get; set; }
public Nullable<int> FormatFileID { get; set; }
public bool UseDummyBarcode { get; set; }
public bool Samples { get; set; }
public string PartNo { get; set; }
public string ProductEAN { get; set; }
public string PONo { get; set; }
public string ImportedFileList { get; set; }
public bool ExportedToLake { get; set; }
public Nullable<int> TotalPalletsOverride { get; set; }
public virtual CardType CardType1 { get; set; }
public virtual FormatFile FormatFile { get; set; }
public virtual ICollection<Item> Items { get; set; }
public virtual SG360JobNos SG360JobNos { get; set; }
public virtual ICollection<Reprint> Reprints { get; set; }
public virtual ICollection<Scan> Scans { get; set; }
public virtual ICollection<LabelType> LabelTypes { get; set; }
}
}
and here's my jobs controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PSAMVC.Models;
using System.Data.SqlClient;
using System.Configuration;
namespace PSAMVC.Controllers
{
public class JobsController : Controller
{
private PSAMVCEntities db = new PSAMVCEntities();
// GET: Jobs
public ActionResult Index()
{
var jobs = db.Jobs.Include(j => j.CardType1).Include(j => j.FormatFile).Include(j => j.SG360JobNos);
return View(jobs.ToList());
}
// GET: Jobs/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
return View(job);
}
// GET: Jobs/Create
public ActionResult Create()
{
ViewBag.CardType = new SelectList(db.CardTypes, "ID", "Description");
ViewBag.FormatFileID = new SelectList(db.FormatFiles, "ID", "Name");
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo");
return View();
}
// GET: CreateBundlesAndCartons
public ActionResult CreateBandC(Int32 id)
{
string ReturnMessage;
ReturnMessage = "";
using (SqlConnection connection = new SqlConnection())
{
//string connectionStringName = this.DataWorkspace.CooperData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings["PSAContext"].ConnectionString;
string procedure = "PSA.dbo.CreateBundlesAndCartons";
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = 300;
command.Parameters.Add(
new SqlParameter("#JobID", id));
SqlParameter ErrorString = new SqlParameter("#ErrorString", ReturnMessage);
ErrorString.Direction = ParameterDirection.Output;
ErrorString.Size = 4000;
command.Parameters.Add(ErrorString);
connection.Open();
command.ExecuteNonQuery();
// Save Outout Param
ReturnMessage = ErrorString.Value.ToString();
#ViewBag.Results = ReturnMessage;
}
}
//return Content("You requested the to create bundles and cartons for job ID " + id.ToString() + "<br />Result: " + ReturnMessage + "<br /> Return to Jobs");
return PartialView("_SPResults");
}
// GET: Jobs/ExportToLake/5
public ActionResult ExportToLake(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo", job.JobNo);
return View(job);
}
// GET: ExportToLake1
public ActionResult ExportToLake1(Int32 id, Int64 StartSeqNo, Int64 EndSeqNo, Boolean ReverseOrder, String FileNameSuffix)
{
string ReturnMessage;
ReturnMessage = "";
using (SqlConnection connection = new SqlConnection())
{
//string connectionStringName = this.DataWorkspace.CooperData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings["PSAContext"].ConnectionString;
string procedure = "PSA.dbo.ExportToLakeBulk";
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = 1200;
command.Parameters.Add(
new SqlParameter("#JobID", id));
command.Parameters.Add(
new SqlParameter("#ReverseOrder", ReverseOrder));
command.Parameters.Add(
new SqlParameter("#StartSeqNo", StartSeqNo));
command.Parameters.Add(
new SqlParameter("#EndSeqNo", EndSeqNo));
command.Parameters.Add(
new SqlParameter("#Suffix", FileNameSuffix));
SqlParameter ErrorString = new SqlParameter("#ErrorString", ReturnMessage);
ErrorString.Direction = ParameterDirection.Output;
ErrorString.Size = 4000;
command.Parameters.Add(ErrorString);
connection.Open();
command.ExecuteNonQuery();
// Save Outout Param
ReturnMessage = ErrorString.Value.ToString();
#ViewBag.Results = ReturnMessage;
}
}
//return Content("You requested the to create bundles and cartons for job ID " + id.ToString() + "<br />Result: " + ReturnMessage + "<br /> Return to Jobs");
return PartialView("_SPResults");
}
// POST: Jobs/ExportToLake
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ExportToLake2([Bind(Include = "ID,StartSeqNo,EndSeqNo,ReverseOrder")] Job job)
{
if (ModelState.IsValid)
{
//db.Jobs.Add(job);
//db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CardType = new SelectList(db.CardTypes, "ID", "Description", job.CardType);
ViewBag.FormatFileID = new SelectList(db.FormatFiles, "ID", "Name", job.FormatFileID);
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo", job.JobNo);
return View(job);
}
// POST: Jobs/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,JobNo,VersionRef,PSAJobRef,TotalCopies,CopiesPerBundle,CopiesPerCarton,CopiesPerMasterCarton,CopiesPerPallet,CardType,CardTitle,CardMMYY,StartSerialNo,StartBundleNo,StartCartonNo,StartMasterCartonNo,StartPalletNo,ProductUPC,PackagingUPC,PreProcessed,Completed,FormatFileID,UseDummyBarcode,Samples,PartNo,ProductEAN,PONo,ImportedFileList,ExportedToLake,TotalPalletsOverride")] Job job)
{
if (ModelState.IsValid)
{
db.Jobs.Add(job);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CardType = new SelectList(db.CardTypes, "ID", "Description", job.CardType);
ViewBag.FormatFileID = new SelectList(db.FormatFiles, "ID", "Name", job.FormatFileID);
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo", job.JobNo);
return View(job);
}
// GET: Jobs/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
ViewBag.CardType = new SelectList(db.CardTypes, "ID", "Description", job.CardType);
ViewBag.FormatFileID = new SelectList(db.FormatFiles, "ID", "Name", job.FormatFileID);
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo", job.JobNo);
return View(job);
}
// POST: Jobs/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,JobNo,VersionRef,PSAJobRef,TotalCopies,CopiesPerBundle,CopiesPerCarton,CopiesPerMasterCarton,CopiesPerPallet,CardType,CardTitle,CardMMYY,StartSerialNo,StartBundleNo,StartCartonNo,StartMasterCartonNo,StartPalletNo,ProductUPC,PackagingUPC,PreProcessed,Completed,FormatFileID,UseDummyBarcode,Samples,PartNo,ProductEAN,PONo,ImportedFileList,ExportedToLake,TotalPalletsOverride")] Job job)
{
if (ModelState.IsValid)
{
db.Entry(job).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CardType = new SelectList(db.CardTypes, "ID", "Description", job.CardType);
ViewBag.FormatFileID = new SelectList(db.FormatFiles, "ID", "Name", job.FormatFileID);
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo", job.JobNo);
return View(job);
}
// GET: Jobs/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
return View(job);
}
// POST: Jobs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Job job = db.Jobs.Find(id);
db.Jobs.Remove(job);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Firstly the server side code should not assume that the values being passed are valid. Always validate the values and handle errors correctly. Client side validation can be bypassed.
In terms of providing instant feedback, one approach is to have an action on a controller that accepts the value to validate as a parameter and returns json containing whether the value was valid and if not the error.
This action can then be called on the input fields blur event or change even providing close to real time feedback on whether the values are valid.
Another approach is to have the valid values determined during the page rendering process and embedded into the client side validation framework if you have one (or use custom JS).
Client Code
function performValidate(data, url) {
var result = $.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
if (!data.success) {
//HandleIncorrectValue
}
//HandleCorrectValue
},
error: function (data) {
//HandleError
}
});
Controller Code
[HttpPost]
public ActionResult Validate(int value)
{
var response = ValidateValue(value);
return Json(new { success = response.Success, message = response.Message });
}

Create ActionResult for save throws error saying The model item passed into the dictionary is of type

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");
}

Resources