My Post call does not return the correct Model type. It always use the baseObject instead of the correct derived object that I passed in from the Get

RestaurantViewModel.cs

public class RestaurantViewModel{
   public Food BaseFoodObject{get;set;}
}

Food.cs

public class Food{
  public string Price{get;set;)
}

Bread.cs -- Inherit from Food

public class Bread:Food{
    public int Unit{get;set;} 
}

Milk.cs -- Inherit from Food

public class Milk:Food{
   public string Brand{get;set}
}

Editor For Template for Bread. Display the unit and allow user to edit

Index.html

@Model RestaurantViewModel

@using(Html.BeginForm("SaveFood", "Food"))
{
  @Html.EditorFor(m=>m.BaseFoodObject)
 <input type="submit" value="Process"/>
}

Bread.cshtml

@Model Bread
<div> 
   @Html.TextboxFor(bread=>bread.Unit)
</div>

FoodController.cs

public ActionResult Index(){
  Bread bread = new Bread(){
     Price = "$10",
     Unit = 1
  }
  RestaurantViewModel viewModel = new RestaurantViewModel(){
     BaseFoodObject = bread
  }
  return View(viewModel);
}

public ActionResult Post(RestaurantViewModel viewModelPost)
{
// When I inspect the viewModelPost, there is no attribute for unit
}

Final Result: 1. The display looks correct. EditorFor is smart enough to pick the correct editor template and display the value correctly 2. The Save does not work. The Unit attribute of Bread Object does not get passed in with the RestaurantViewModel. The reason for that is the RestaurantViewModel used the Food object instead of Bread

I hope there is away to modify the EditorFor and tell it to use the Model in the View or the Object Type that I passed in when I display it.

Thanks

Related posts

Recent Viewed