I have page, which allows me to add interesting places (POI), based on the different predifined categories:
Models
public class POI
{
public long Id { get; set; }
public string TitleNor { get; set; }
public string TitleEng { get; set; }
public Category Category { get; set; }
public string DescriptionNor { get; set; }
public string DescriptionEng { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public string ImagePath { get; set; }
public HttpPostedFileBase UploadedPhoto { get; set; }
}
public class Category
{
public int Id { get; set; }
public string TitleNor { get; set; }
public string TitleEng { get; set; }
}
Create
@Html.DropDownListFor(model=>model.Category.Id, ViewBag.Categories as SelectList, "", new { @class = "form-control" })
Controller
List<Category> categories = new List<Category>();
var categoryQry = from d in db.Categories
select d;
categories.AddRange(categoryQry.Distinct());
ViewBag.Categories = new SelectList(categories, "Id", "TitleNor");
return View(pOI);
So when I create a new POI, I get the following state of POI:
TitleEng and TitleNor = null. So if I will add a new POI object, the Category object, only with the Id, will be added as well.
So Category is not mapped as a property, only it's ID filed is. As I understand one of the solutions is to change POI model and instead of property Category have only CategoryID. But how can I get a proper mapping, if I don't want to change a model? Thanks in advance.
model=>model.Categorybecause model.category is a complex object. A<select>control only posts back a single value. If you need the category fully populated, then you have to get it again from the database.