views:

25

answers:

1

Hi,

I have a viewmodel that contains a product and SelectList of categories.

public class AdFormViewModel
{
    public AmericanAds.Model.Ad Ad { get; set; }
    public SelectList Categories { get; set; }

    public AdFormViewModel(AmericanAds.Model.Ad ad, SelectList categories)
    {
        Ad = ad;
        Categories = categories;
    }
}

When adding a new product, if validation fails for category dropdown I get below error message.

The model item passed into the dictionary is of type 'AmericanAds.Model.Ad' but this dictionary requires a model item of type 'AmericanAds.Controllers.AdFormViewModel'.

Here is the controller for create action.

public ActionResult Create()
    {
        AdFormViewModel data = new AdFormViewModel(
            null,
            new SelectList(_repository.CategoryList().ToList(), "CategoryId", "CategoryName")
            );

        return View(data);
    } 

    //
    // POST: /Ad/Create

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Ad ad)
    {
        if (ModelState.IsValid)
        {
            try
            {
                _repository.AddAd(ad);

                return RedirectToAction("Index");
            }
            catch
            {
                return View(ad);
            }
        }
        else
        {
            return View(ad);
        }
    }

What am I missing?

As you can tell, I am very new to ASP.Net MVC.

Thanks!

A: 

It's because your Create view requires a model of type AdFormViewModel but in your Create action (the one with the [AcceptVerbs(HttpVerbs.Post)] attribute) you return a model of type Ad (see the lines where it says return View(ad)).

Like the exception message says ; It requires an AmericanAds.Controllers.AdFormViewModel but you are sending an AmericanAds.Model.Ad.

And no, I don't think this has anything to do with the validation.

çağdaş
Spot on Cagdas, thanks my fellow country man ;)
hhastekin
@hhastekin, You're welcome :)
çağdaş