Forum Moderators: open

Message Too Old, No Replies

MVC, AutoMapper, and Custom dropdown

         

andrewsmd

2:01 am on Oct 18, 2013 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I asked this on the MVC forums but got no response. I'm hoping someone here can help me out.

I'm learning MVC so bear with me. I have a category table that has a parent category field. So, in the edit or add views, you need a dropdown of all the other categories. I was able to accomplish this by manually mapping my CategoryViewModel to my Category Model. However, I want to start using automapper and I just can't pin down the syntax. Here's my view model.

/// <summary>
/// this class contains all of the data for the cateogry data it also handles the error detection and correction
/// </summary>
public class CategoryViewModel
{

public int categoryId { get; set; }

[Required(ErrorMessage="Please enter a category name")]
public string categoryName { get; set; }

[Required(ErrorMessage = "Please select a category type")]
public int? categoryType { get; set; }

[Required(ErrorMessage = "No parent category")]
public Dictionary<int, string>parentCategory { get; set; }

[Required(ErrorMessage = "Please select a category color")]
public string color { get; set; }

[Required(ErrorMessage = "Please enter a category order")]
public int? order { get; set; }

public bool deleted { get; set; }

public string message { get; set; }

}//CategoryViewModel

Here's my code right now

public ActionResult Edit(int id)
{

var category = DataAccess.GetCategoryById(id);

var allCats = DataAccess.GetActiveCategories();

CategoryViewModel cat = new CategoryViewModel
{
categoryName = category.Name,
categoryType = category.CategoryType,
order = category.sortOrder,
parentCategory = allCats.Where(c=> c.CategoryId != id).ToDictionary(x => x.CategoryId, y => y.Name),
color = category.color
};

if (category == null)
{
return View("NotFound");
}//if
else
{
return View(cat);
}//if category == null

}//Edit


And I'm just trying to pin down how I'd do that with automapper. Not really clear on what two things I'm supposed to be passing into the ForMember

AutoMapper.Mapper.Map(Category, CategoryViewModel);
Mapper.CreateMap<Category, CategoryViewModel>().ForMember(c => c.parentCategory = allCats.Where(c=> c.CategoryId != id).ToDictionary(x => x.CategoryId, y => y.Name);

xiaoyuandlg

7:52 am on Jan 22, 2014 (gmt 0)

10+ Year Member



I've read a lot about C# dropdown list and dropdown list tutorials. But, I still can not catch your question.

[edited by: Ocean10000 at 2:31 pm (utc) on Jan 22, 2014]
[edit reason] removed Links [/edit]

andrewsmd

2:01 pm on Jan 22, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I was just trying to bind a dropdown. I just ended up creating functions in my controller that returned selectlists and bound the dd to that.