Value cannot be null - asp.net-mvc

I have written ASP.NET MVC Code for CRUD but while Updating,Deleting and Details the page is throwing the error as value can not be null.my code is as follows:
public ActionResult Edit(int id=0)
{
var alb=db.Albums.FirstOrDefault(x=>x.AlbumId==id);
return View(alb);
}
public ActionResult Detail(int id=0)
{
var alb=db.Albums.Find(id);
return View(alb);
}
public ActionResult Delete(int id=0)
{
var album = db.Albums.Find(id);
return View(album);
}
and my Model is
public class Album
{
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
public string AlbumTitle { get; set; }
public String Price { get; set; }
public String AlbumArtUrl { get; set; }
public Genre Genre { get; set; }
public Artist Artist { get; set; }
}
This is because the variable alb and album is showing me the null value its not getting any ID.
so suggest me on this.

This is because the variable alb and album is showing me the null
value its not getting any ID
If there is no record in your database then you should handle it gracefully in code. You should have something like:
var alb=db.Albums.FirstOrDefault(x=>x.AlbumId==id);
if (alb==null) {
// TempData, simplest way to give you an example
TempData["error_msg"] = "the record does not exists";
return RedirectToAction("index", "error");
}
return View(alb);
in your ErrorController
public ActionResult Index() {
ViewBag.ErrorMsg = TempData["error_msg"];
return View();
}
in the view (Index.cshtml) for your error controller
<h1>You have been, or trying to be, a naughty boy</h1>
<p>#ViewBag.ErrorMsg</p>
This is not the most elegant solution though but good enough to get you started. I think the most important part of my answer is not the code I gave you but the suggestion to handle that kind of situation (null values / missing or invalid records) in code.

Related

ASP:NET MVC Summary of a field as a validation for the field itself (Recursiveness)

I Have the following class in a model:
public partial class OrganizationUnit
{
public string code{ get; set; }
public int OrganizationCod { get; set; }
public string name { get; set; }
public string ParentUnitCode{ get; set; }
public int level{ get; set; }
public string author{ get; set; }
public System.DateTime CreateDtStmp{ get; set; }
public int Status { get; set; }
public decimal weighing { get; set; }
[ForeignKey("status")]
public virtual Status UnitStatus { get; set; }
public virtual Organization Organization { get; set; }
public virtual ICollection<OrganizationUnit> OrganizationUnit1{ get; set; }
[ForeignKey("ParentUnitCode")]
public virtual OrganizationUnit OrganizationUnit2{ get; set; }
public OrganizationUnit ()
{
CreateDtStmp= DateTime.Now;
author = HttpContext.Current.User.Identity.Name.Substring(4,HttpContext.Current.User.Identity.Name.Length - 4);
}
}
Before inserting a new record I need to validate sum(weighing) can not exceed 100 including the attempted new record, considering only the records with the same ParentUnit.
Can this be done in the model or should it be done in the controller?
this is the saving controller part (basically is what is autogenerated by VS),consider that the view will send the corresponding parameter to the method:
private SAIM_IPM_DVContext db = new SAIM_IPM_DVContext();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(OrganizationUnit organizationunit)
{
if (ModelState.IsValid)
{
db.OrganizationUnit.Add(organizationunit);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(organizationunit);
}
If OrganizationUnit1 is the collection of all other units with the same ParentUnit, you can perform the check in the ViewModel by implementing IValidatableObject:
using System.ComponentModel.DataAnnotations;
public partial class OrganizationUnit : IValidatableObject {
/* properties etc... */
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (OrganizationUnit1.Sum(o => o.weighing) + this.weighing > 100.0) {
yield return new ValidationResult(
"Sum of weightings would exceed 100.",
new[] { "weighing" });
}
}
}
Note that this assumes that the weighing is posted back for all units in the OrganizationUnit1 collection (e.g. as hidden fields) so it is accessible when this check is performed by the MVC pipeline (this is done before your POST action will be hit).
If this check fails, ModelState.IsValid will be false in the controller.
If you have no access to the other units in the Viewmodel, you will have to fetch them from the DB in the controller and perform the check there.
After a while and tries I came up with this solution works perfect, however I am not sure is the best practice. This is on the controller class
public ActionResult Create(OrganizationUnit organizationunit)
{
decimal weighingsum= 0;
foreach (var val in db.OrganizationUnit.Where(t => t.ParentUnitCode== organizationunit.ParentUnitCode))
{
weighingsum+= val.weighing ;
}
weighingsum+= organizationunit.weighing ;
if (weighingsum > 100)
{
ModelState.AddModelError("", "Weighing sum can not exceed 100 for a Parent Unit");
}
else
{
if (ModelState.IsValid)
{
db.OrganizationUnit.Add(organizationunit);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(organizationunit);
}
should anyone comes up with a better solution, please do share I'll appreciate it.

How do I use an edit viewmodel in MVC?

I have been struggling with this for some time. I have a model and an edit view model so I can allow the user to both see the image that was uploaded before and upload a replacement. Everything works fine until I get to the db.Entry portion. The error is:
The entity type EditCardViewModel is not part of the model for the current context.
If I try to add EditCardViewModel to the DbContext, it wants a key and a table, which isn't going to happen. The ViewModel is just a way to pass data. How do I tell it to use the Cards context when saving from this ViewModel?
Controller Edit Get:
public ActionResult Edit(int id = 0)
{
Card card = db.Cards.Find(id);
ViewData["Abilities"] = card.CardAbilities.Select(a => a.AbilityID);
if (card == null)
{
return HttpNotFound();
}
var editview = new EditCardViewModel(card);
{
}
return View(editview);
}
Controller Edit Post:
[HttpPost]
public ActionResult Edit(EditCardViewModel card)
{
if (ModelState.IsValid)
{
if(card.ImageUpload != null)
{
string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images");
savedFileName = Path.Combine(savedFileName, Path.GetFileName(card.ImageUpload.FileName));
card.ImageUpload.SaveAs(savedFileName);
card.Cards.ImageUrl = "\\Images\\" + Path.GetFileName(card.ImageUpload.FileName);
}
db.Entry(card).State = EntityState.Modified; //ERROR - Entity Type is not part of context
db.SaveChanges();
Edit ViewModel:
public class EditCardViewModel
{
public Card Cards { get; set; }
public HttpPostedFileBase ImageUpload { get; set; }
public IEnumerable<SelectListItem> Abilities { get; set; }
public int[] SelectedAbilities { get; set; }
public IEnumerable<SelectListItem> Rarities { get; set; }
public int SelectedRarities { get; set; }
public IEnumerable<SelectListItem> MainTypes { get; set; }
public int SelectedMainTypes { get; set; }
public IEnumerable<SelectListItem> SubTypes { get; set; }
public int SelectedSubTypes { get; set; }
public IEnumerable<SelectList> CardSets { get; set; }
public int SelectedCardSets { get; set; }
public Rarity Rarity { get; set; }
public MainType MainType { get; set; }
public SubType SubType { get; set; }
public CardSet CardSet { get; set; }
public EditCardViewModel() { } //NEEDED OR PARAMETERLESS CONSTRUCTOR ERROR
public EditCardViewModel(Card card) //NEEDED OR CANNOT PASS CARD MODEL
{
Cards = card;
}
}
The problem is that your view model is not recognised by Entity Framework - it has no idea that EditCardViewModel is meant to be a representation of a Card. It's a bit unclear from your view model exactly what you are doing with it but you either need to create a new Card object and use that:
var newCard = new Card
{
Id = card.Id //for example
};
Or possibly use the Cards property of your view model as that is of the correct type.

MVC Updates over values with NULL

This is probably very simple for most MVC programmers, so maybe you can help me out. I have a table called Images in the database with nine columns. On my UPDATE, I just have three I want to mess with (ImageName, ImagePath, CourseID). After I post back with UPDATE, it sets the other six columns to NULL. I'm not sure how to handle this in MVC.:
My ViewModel:
public class GalleryViewModel
{
public Image _image { get; set; }
}
My Model:
public partial class Image
{
public int ImageID { get; set; }
public string ImageName { get; set; }
public string ImagePath { get; set; }
public Nullable<int> CourseID { get; set; }
public string UserId { get; set; }
public Nullable<System.DateTime> CreateDate { get; set; }
public string ImageType { get; set; }
public string ImageSize { get; set; }
public string FriendlyName { get; set; }
public virtual Cours Cours { get; set; }
}
My Controller:
[HttpGet]
public ActionResult UploadImageEdit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var model = new GalleryViewModel
{
_image = db.Images.Find(id),
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadImageEdit(GalleryViewModel galleryViewModel)
{
if (ModelState.IsValid)
{
db.Entry(galleryViewModel._image).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("UploadImageIndex");
}
return View(galleryViewModel);
}
After reading other examples and becoming more familiar with ViewModel to controller, I got the UPDATE to work by doing the following:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadImageEdit(int id, GalleryViewModel galleryViewModel)
{
if (ModelState.IsValid)
{
var imageContext = db.Images.Find(id);
imageContext.FriendlyName = galleryViewModel._image.FriendlyName;
db.Entry(imageContext).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("UploadImageIndex");
}
return View(galleryViewModel);
}
I hope this helps other folks out!

MVC3 - Reading GET Variables Into Controller Action

I have a controller action /Responses/Insert and want to be able to GET variables from URL and save them to my database.
The URL will look like this:
/Responses/Insert?pass=blah&msisdn=blah&sender=blah&message=blah&dca=blah&msg_id=blahsource_id=blah
Here is my model:
public class Response
{
public int ResponseId { get; set; }
public string msisdn { get; set; }
public string sender { get; set; }
public string message { get; set; }
public string dca { get; set; }
public string msg_id { get; set; }
public string source_id { get; set; }
}
Can anyone offer advice on how to code my controller action?
//
// GET: /Response/Insert
public ActionResult Insert()
{
return View();
}
Thanks very much!
Paul
EDIT 1 - SOLVED (Thanks LukLed)
public ActionResult Insert(Response response)
{
if (ModelState.IsValid)
{
responseRepository.InsertOrUpdate(response);
responseRepository.Save();
return RedirectToAction("Index");
}
else
{
return View();
}
}
Try this:
public ActionResult Insert(Response response)
{
return View();
}
Model binder will handle turning GET values into Response object.

ASP.NET EditorTemplate DropdownList

Every time I add a new App It creates a new AppCategory. I am seriously screwing this up somehow
code first entity framework objects
public class AppCategory
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<App> apps { get; set; }
}
public class App
{
public int ID { get; set; }
public string Name { get; set; }
public AppCategory Category { get; set; }
}
Editor Template (I would love to just make just one Foreign Key EditorTemplate)
#inherits System.Web.Mvc.WebViewPage
#Html.DropDownList("Category", LIG2010RedesignMVC3.Models.Repo.GetAppCategoriesSelect())
and of course the repository
public static IEnumerable<SelectListItem> GetAppCategoriesSelect()
{
return (from p in GetAppCategories()
select new SelectListItem
{
Text = p.Name,
Value = p.ID.ToString(),
});
}
public static ICollection<AppCategory> GetAppCategories()
{
var context = new LIGDataContext();
return context.AppCategories.ToList();
}
Every time I add a new App It creates a new AppCategory I am seriously screwing this up somehow
Adding more debug info
#inherits System.Web.Mvc.WebViewPage
#Html.DropDownList("", LIG2010RedesignMVC3.Models.Repo.GetAppCategoriesSelect())
gives me a validation message on the post
Parameters application/x-www-form-urlencoded
Category 1
Name 8
Validation error The value '1' is invalid.
This makes sense because Category should be an object not an integer.
Controller Code as asked for
pretty sure this isnt the problem as it came from MVCScaffold
[HttpPost]
public ActionResult Create(App d)
{
if (ModelState.IsValid)
{
context.Apps.Add(d);
context.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
My model was incorrectly set up ... virtual ICollection and just the foreign key id for the sub and everything worked... changes below
Model
public class AppCategory
{
public int ID { get; set; }
public string Name { get; set; }
public **virtual** ICollection<App> Apps { get; set; }
}
public class App
{
public int ID { get; set; }
********************************************
[UIHint("AppCategory")]
public int AppCategoryID { get; set; }
********************************************
public string Name { get; set; }
}
public class LIGDataContext : DbContext
{
public DbSet<AppCategory> AppCategories { get; set; }
public DbSet<App> Apps { get; set; }
}
/Views/Shared/EditorTemplates/AppCategory.cshtml
#inherits System.Web.Mvc.WebViewPage
#Html.DropDownList("", LIG2010RedesignMVC3.Models.Repo.GetAppCategoriesSelect())
AppController
[HttpPost]
public ActionResult Create(App d)
{
if (ModelState.IsValid)
{
this.repository.Add(d);
this.repository.Save();
return RedirectToAction("Index");
}
return View();
}
If you bind your dropDownList to Category.Id, you'll at least get the selected value into that filed, but nothing else in your Category Object.
The model binder cannot create the AppCategory object from the form collection in your Create action because the form only has an ID for that object (the other properties of AppCategory are not there).
The quickest solution would be setting the Category property of your App object manually, like this :
[HttpPost]
public ActionResult Create(App d) {
int categoryId = 0;
if (!int.TryParse(Request.Form["Category"] ?? String.Empty, out categoryId) {
// the posted category ID is not valid
ModelState.AddModelError("Category",
"Please select a valid app category.")
} else {
// I'm assuming there's a method to get an AppCategory by ID.
AppCategory c = context.GetAppCategory(categoryID);
if (c == null) {
// couldn't find the AppCategory with the given ID.
ModelState.AddModelError("Category",
"The selected app category does not exist.")
} else {
// set the category of the new App.
d.Category = c;
}
}
if (ModelState.IsValid)
{
context.Apps.Add(d);
context.SaveChanges();
return RedirectToAction("Index");
}
return View();
}

Resources