Giorgi Tsertsvadze
Giorgi Tsertsvadze

Reputation: 433

How to render create view when model has reference to another model?

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?

Upvotes: 0

Views: 376

Answers (1)

TAHA SULTAN TEMURI
TAHA SULTAN TEMURI

Reputation: 5261

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) {          

    }
}); 

Upvotes: 1

Related Questions