0

I am trying to learn ASP.NET MVC. Currently I want to render a create page of a model, which has reference to another model, and make user select the other model from drop down list. To be more specific, here is the code for Category model

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}

And here is the code of Food model

public class Food
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category Category { get; set; }
}

Consider I have an in memory list of categories called categories and I want to make sure that when I send create view to user with return View(); in HomeController's Create method he gets not only the name to choose but also the drop down of categories. Also consider that in near future I want to generate the tables of database according to these classes (Entity Frameworks code first approach) so adding properties to the classes doesn't seem like a good idea. How can I do that?

Hossein Golshani
  • 1,847
  • 5
  • 16
  • 27
Giorgi Cercvadze
  • 403
  • 1
  • 7
  • 23
  • 1
    What have you tried, and what is not working? Suggest you refer the code in [this Q/A](https://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) for example of how to generate a dropdownlist –  Oct 12 '18 at 21:19

1 Answers1

1

You can make use of viewBag to pass more than one model from controller to view like this

Controller

Public ActionResult Index()
{  
 viewbag.Childone=Childone();
 viewbag.Childtwo=Childtwo()
 return View(parentModel);
}

[HttpPost]
public ActionResult Index(ParentModel parentModel,Childone child_one ,Childtwo child_two)
 {
  //do something with models passed....
 }

View

 @model parentModel

 @{
    Childone  = viewbag.Childone as Childone;
    Childtwo  = viewbag.Childtwo as Childtwo;
  }

   //just use these models......like
 //this is Main parent model
 <p>@Model.propertyname</p> 

   //these are child
 <p>@Childone.propertyname</p>

 <p>@Childtwo.propertyname</p>

On Model Submit Button Click

var parentModel = [
  { id: 1, color: 'yellow' },
 ];
 var child_one = [
    { id: 1, color: 'yellow' },

];   

 var child_two = [
    { id: 1, color: 'yellow' },

];      



$.ajax({
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    url: '/Home/Index',
    data:JSON.stringify(parentModel:parentModel child_one:child_one,child_two:child_two),
    success: function () {          

    },
    failure: function (response) {          

    }
}); 
TAHA SULTAN TEMURI
  • 4,031
  • 2
  • 40
  • 66