1

I have a problem with DropDownlist in MVC I use ModelView in my application and this is my code

namespace MedicallexiconProject.ViewModel
{
    public class WordViewModel
    {
        private readonly ICategoryService _categoryService;
        public WordViewModel(ICategoryService categoryService)
        {
            _categoryService = categoryService;
            var selectList = _categoryService.GetAllCategorysSelectList().
                Select(x => new SelectListItem
                {
                    Text = x.Name,
                    Value = x.ID.ToString()
                }).ToList();
            Categories = selectList;
        }

        public WordViewModel()
        {

        }
        public string Name { get; set; }
        private IList<SelectListItem> _categories;
        public IList<SelectListItem> Categories
        {
            get
            {
                if (_categories == null)
                {
                    _categories = new List<SelectListItem>();
                }
                return (_categories);
            }

            set { _categories = value; }
        }
    }
}

and this is my controller

[HttpGet]
public ActionResult Create()
{
    var wordViewModel = new WordViewModel(_categoryService);
    ViewBag.CategoryID = wordViewModel.Categories;
    return View();
}

[HttpPost]
public ActionResult Create(WordViewModel wordViewModel)
{
    Mapper.CreateMap<WordViewModel, Word>();

    var word = new Word();
    Mapper.Map(wordViewModel, word);

    if (ModelState.IsValid)
    {
        _wordService.AddNewWord(word);
        _uow.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(wordViewModel);
}

Now how can I insert dropdownlist in my View?

1
  • 1
    You should not put logic in your ViewModel, logic that fills your ViewModel should go in your controller action. The ViewModel should be a dumb class with no business logic or data access logic. Commented Jun 17, 2012 at 16:34

2 Answers 2

3

As AlfalfaStrange mentioned, you should not add logic in your ViewModel. That makes it ugly ! Keep your ViewModel simple POCO.

Add one more property in your ViewModel called "SelectedCategoryID" like this

public class WordViewModel
{
  public int SelectedCategoryID { set;get;}
  public IList<SelectListItem> Categories { set;get;}
  public string Name { set;get;}
}

Initialize your Items (Categories) of your ViewModel in your GET method. Here i am calling a method called GetCategories which returns a list of categories.I can simply call the method wherever i want.

public ActionResult Create()
{
   var model=new WordViewModel();
   model.Categories=YourService.GetCategories();
   return View(model);
}

In your strongly typed Create view , use this

@model WordViewModel
using(@Html.BeginForm())
{

  @Html.DropDownFor(x=>x.SelectedCategoryID,
               new SelectList(Model.Categories,"Value","Text"),"Select Category")
  <input type="submit" value="Save" />
}

In your HttpPost action method , you can check for wordViewModel.SelectedCategoryID for the selected value.

[HttpPost]
public ActionResult Create(WordViewModel wordViewModel)
{
   if(ModelState.IsValid)
   {
     //Checck for wordViewModel.SelectedCategoryID here now
   }
   //some validation failed. Let's reload the category data again.
   wordViewModel.Categories=YourService.GetCategories();
   return View(wordViewModel);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hello.can i retun from view a Category Object to mapping?
@MohammadJafari mapping means ?
var category = _categoryService.GetByID(wordViewModel.SelectedCategoryID); word.Category = category;
var category = _categoryService.GetByID(wordViewModel.SelectedCategoryID); word.Category = category;
0

It's absolutely fine to include code that loads a dropdown list in your view model. A select list and a drop down are both "view" items.... they are not related to business logic and your controller and model need not know anything about SelectLists or SelectListItems or DropDownList, etc.

1 Comment

Please elaborate why :0. This post is a year old you must have something to add so please add all you know :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.