Click here to Skip to main content
15,868,164 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi!

I am getting the following error. Can anyone help me solve this error?
The code is:
C#
public class CategoryController : Controller
{
	//
	// GET: /Category/
	ProductsDbEntities ctx;

	public CategoryController ( )
	{
		ctx = new ProductsDbEntities( );
	}

	public ActionResult Index ( )
	{
		try
		{
			var categoryList = ctx.Categories.ToList( );
			return View( categoryList );
		}

		catch ( Exception ex )
		{
			throw ex;
		}
	}
}

The code for the View is:
HTML
@model MvcSession.Models.CategoryDetails

@{
    ViewBag.Title = "SearchProducts";
}

@using (Html.BeginForm())
{
    @Html.EditorFor(cat => cat.CategoryId);
         <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Search" class="btn btn-default" />
            </div>
        </div>
}

I am getting the following error when I run the application :-

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[MvcSession.EntityModel.Category]', but this dictionary requires a model item of type 'MvcSession.Models.CategoryDetails'.
Posted
Updated 15-Apr-15 0:15am
v2

It should be clear...
You are returning a list of Categories from the model, but the view expect to get CategoryDetails!
So the model and the view are not synchronized!!!
 
Share this answer
 
The message is clear.
HTML
@model MvcSession.Models.CategoryDetails

You have refered the model CategoryDetails in view, but sending categoryList, which is not matching with the model.

Please send an object of CategoryDetails model. It would work.
 
Share this answer
 
Comments
Member 11185261 15-Apr-15 9:31am    
I have made the necessary changes as suggested by you and came up with the following code. Still it raises the same error. Kindly go through the code and let me know where I have gone wrong.

public ActionResult Index()
{
try
{
var categoryList = ctx.Categories.ToList();
List<categorydetails> Details = new List<categorydetails>();
foreach (var items in categoryList)
{
var cd = new CategoryDetails();
cd.CategoryId = items.CategoryId;
cd.CategoryName = items.CategoryName;
Details.Add(cd);
}
return View(Details);
}

catch (Exception ex)
{
throw ex;
}
}
You need to send object of "CategoryDetails" class or a not a "List".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900