In my controller i am creating a new subcategory object and saving it to my database like this:
[Authorize(Roles = "administrator")]
[HttpPost]
public ActionResult Create(CategoryViewModel viewmodel, HttpPostedFileBase Icon)
{
SubCategory subcategory = viewmodel.subcategory;
subcategory.Category = categorycontroller.getCategoryByName(viewmodel.SelectedValue);
if (Icon != null && Icon.ContentLength > 0)
{
// extract only the filename
var fileName = Path.GetFileName(Icon.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("../../Content/icons/"), fileName);
Icon.SaveAs(path);
subcategory.Icon = fileName;
}
if (ModelState.IsValid)
{
db.subcategories.Add(subcategory);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(subcategory);
}
After debugging the application i noticed that the controller correctly saves all my data including the reference to a category object in my newly created subcategory.
problem is when i load the data from my db later on the subcategory object is missing its reference to my category object.
my viewmodel looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using SkyLearn.Areas.Categories.Controllers;
namespace SkyLearn.Areas.Categories.Models
{
public class CategoryViewModel
{
public List<SelectListItem> PossibleValues { get; set; }
public string SelectedValue { get; set; }
public SubCategory subcategory { get; set; }
public CategoryController categorycontroller;
public CategoryViewModel()
{
PossibleValues = new List<SelectListItem>();
}
}
}
and my method on the category controller that finds the object:
public Category getCategoryByName(string categoryname)
{
foreach (Category cat in getCategories())
{
if (cat.Title == categoryname)
{
return cat;
}
}
return null;
}
why does my category object reference disappear guys? im in a blind
No comments:
Post a Comment