Get the existing categories from the database (preferrably via a repository, but for brevity I just show the Linq to Entities query):
var db = new YourObjectContextImplementation();
var categories = db.Categories.AsEnumerable();
Forward these to your view via a view model. In your view, you output a form somehow to enable the user to add a classified. Instead of giving them a textbox (or select list) for the category Id, you give them a select list where the value is the id, but the text/inner html is the category name. That way, the user only sees the name, but your action gets an integer parameter passed to it.
UPDATE in response to comment:
I assume you are currently passing a new Classified
object as view model, and then using the EditorFor
helpers? All good, but you should probably wrap the Classified
object in a specific view model, for example a ClassifiedAddModel
as follows:
public class ClassifiedAddModel
{
public Classified NewClassified { get; set; }
public IEnumerable<Category> ExistingCategories { get; set; }
}
Then you can instantiate and populate the ClassifiedAddModel
object in the controller action, pass it along as the model to your view, and build the form using syntax like
<%: Html.EditorFor(Model.NewClassified.Description) %>
<%: Html.EditorFor(Model.Categories "CategoriesEditor") %>
where "CategoriesEditor"
is the name of a custom view model that takes categories and renders a select list with them. The main point with the above example, however, is to show how you can access both properties on the Classified
object, and all the existing categories.