I have a partial view that is contained in a simple index view. When I try to add a new object to my model and update my partial view to display that new object along with existing objects the partial view is rendered outside the page that it's contained?
I'm using AJAX to update the partial view but what is wrong with the following code?
Model:
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
[DataType(DataType.Currency)]
public decimal Price { get; set; }
}
public class BoringStoreContext
{
List<Product> results = new List<Product>();
public BoringStoreContext()
{
Products = new List<Product>();
Products.Add(new Product() { ID = 1, Name = "Sure", Price = (decimal)(1.10) });
Products.Add(new Product() { ID = 2, Name = "Sure2", Price = (decimal)(2.10) });
}
public List<Product> Products {get; set;}
}
public class ProductIndexViewModel
{
public Product NewProduct { get; set; }
public IEnumerable<Product> Products { get; set; }
}
Index.cshtml View:
@model AjaxPartialPageUpdates.Models.ProductIndexViewModel
@using (Ajax.BeginForm("Index_AddItem", new AjaxOptions { UpdateTargetId = "productList" }))
{
<div>
@Html.LabelFor(model => model.NewProduct.Name)
@Html.EditorFor(model => model.NewProduct.Name)
</div>
<div>
@Html.LabelFor(model => model.NewProduct.Price)
@Html.EditorFor(model => model.NewProduct.Price)
</div>
<div>
<input type="submit" value="Add Product" />
</div>
}
<div id='productList'>
@{ Html.RenderPartial("ProductListControl", Model.Products); }
</div>
ProductListControl.cshtml Partial View
@model IEnumerable<AjaxPartialPageUpdates.Models.Product>
<table>
<!-- Render the table headers. -->
<tr>
<th>Name</th>
<th>Price</th>
</tr>
<!-- Render the name and price of each product. -->
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(model => item.Name)</td>
<td>@Html.DisplayFor(model => item.Price)</td>
</tr>
}
</table>
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
BoringStoreContext db = new BoringStoreContext();
ProductIndexViewModel viewModel = new ProductIndexViewModel
{
NewProduct = new Product(),
Products = db.Products
};
return View(viewModel);
}
public ActionResult Index_AddItem(ProductIndexViewModel viewModel)
{
BoringStoreContext db = new BoringStoreContext();
db.Products.Add(viewModel.NewProduct);
return PartialView("ProductListControl", db.Products);
}
}