Partial view - Model binding in ASP.NET MVC 4 - asp.net-mvc

I have 2 models in my MVC 3 application, CustomerOrder and OrderDetail.
My Model OrderDetail is with List.
Model
public class CustomerOrder
{
public int CustomerId { get; set; }
public int NetPrice { get; set; }
public List<OrderDetail> Orderlist { get; set; }
public CustomerOrder()
{
Orderlist = new List<OrderDetail>();
}
}
public class OrderDetail
{
public string ProductName { get; set; }
public int Quantity { get; set; }
public int Price { get; set; }
public int TotalPrice {get{ return Price*Quantity;} }
}
This is My Controller
public ActionResult CustomerOrder()
{
return View();
}
[HttpPost]
public ActionResult CustomerOrder(CustomerOrder SelectedOrder)
{
DataBase dataBase = new DataBase();
var result = dataBase.InsertData(SelectedOrder);
ViewData["result"] = result;
return View();
}
This is My View for CustomerOrder
#model MvcCustomerOrderClass4g.Models.CustomerOrder
#{
ViewBag.Title = "CustomerOrder";
}
<h2>CustomerOrder</h2>
#using (Html.BeginForm()) {
<fieldset>
<legend>CustomerOrder</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CustomerId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CustomerId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.NetPrice)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.NetPrice)
</div>
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
#{
if (ViewData["result"] != "" && ViewData["result"] != null)
{
<script type="text/javascript" lang="javascript">
alert("Data saved Successfully");
</script>
}
}
My Model OrderDetail is with List. How to use it as a list in my view?
Here I want to add OrderDetail model. I also created another view for OrderDetails, for adding it as Partial in CustomerOrder.

The easiest way would be to create an EditorTemplate:
#model OrderDetail
#Html.HiddenFor(m => m.Id)//your model doesn't seem to have an id?
#Html.DisplayFor(m => m.ProductName)
#Html.EditorFor(m => m.ProductName)
Then in your view with the CustomerOrder model just do this:
#Html.LabelFor(model => model.OrderList)
#Html.EditorFor(model => model.OrderList)

Related

why my checkboxes arent generated?

i have the following controller that calls view with template that generates a set of checkboxes
The controller / Action
public class CompoundsController : Controller
{
//
// GET: /Compounds/
testdbDBContext db = new testdbDBContext();
public ActionResult Index()
{
var comps = db.Compounds.Select(e => new CompoundModel { Id=e.Id, Code=e.Code, Name=e.Name, IsSelected = e.IsSelected }).ToList();
return View(new ChemicalsVM { cModel = comps});
}
}
The view
#model mvca1.Models.ChemicalsVM
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ChemicalsVM</legend>
<div class="editor-label">
#Html.LabelFor(model => model.SName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SName)
#Html.ValidationMessageFor(model => model.SName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DName)
#Html.ValidationMessageFor(model => model.DName)
</div>
<div class="editor-label">
#Html.Label("Chemicals")
</div>
<div class="editor-field">
#Html.EditorFor(x=>x.cModel)
#Html.ValidationMessageFor(model => model.cModel)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
the template is:
#model mvca1.Models.CompoundModel
#{
ViewBag.Title = "rmplCompoundDB";
}
#Html.HiddenFor(x=>x.Id)
#Html.HiddenFor(x=>x.Code)
#Html.CheckBoxFor(x=>x.IsSelected, (Model.IsSelected)? new {#checked="checked"}:null)
#Html.LabelFor(x=>x.Name)
when i ran the code instead of generating checkboxes with labels it displays the id numbers (that should be hidden)
here is the video of what happens https://youtu.be/1Z2fwfBgyn8
why it does not display the checkboxes as expected?
UPDATE:
here is my ChemicalsVM
public class ChemicalsVM
{
public int Id { get; set; }
public string SName { get; set; }
public string DName { get; set; }
public List<CompoundModel> cModel { get; set; }
public ChemicalsVM()
{
cModel = new List<CompoundModel>();
}
}
here is the CompoundModel class
public class CompoundModel
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
The html being rendered means the ViewEngine is not finding the EditorTemplate. The template must be named the same as the class (i.e. CompoundModel.cshtml) and be located in either the /Views/Shared/EditorTemplates or /Views/Compounds/EditorTemplates folders.

Adding/Update Related Data ASP.NET MVC 5

I'm new to programming so I'm still learning.
I need to add Items to Grocery from a single view. But I can't get the data to save.
When I hit save I don't get any exceptions, the page just loads but nothing is saved to the
database. Can I get some help/guidance as to what I am doing wrong?
Data Class
public class Grocery
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Item> Items { get; set; }
}
public class Item {
public int ItemId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
View Model
public class GroceryViewModel
{
public Grocery Grocery { get; set; }
public virtual Item Item { get; set; }
public GroceryViewModel(int GroceryId)
{
using (var db = new MyContext())
{
Grocery = db.Groceries
.Include("Items")
.SingleOrDefault(a => a.Id == GroceryId);
}
}
}
Controller
public ActionResult Edit(int GroceryId, GroceryViewModel groceryViewModel)
{
var model = new GroceryViewModel(GroceryId);
var plusItems = new Item
{
Name = groceryViewModel.Item.Name,
Description = groceryViewModel.Item.Description,
};
db.Items.Add(plusItems);
db.SaveChanges();
return RedirectToAction(model);
View
#model Project.Models.GroceryViewModel
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Groceries</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Item.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Item.Name)
#Html.ValidationMessageFor(model => model.Item.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Item.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Item.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<p>
<input type="submit" value="Add Item" />
</p>
</fieldset>
try
using (var db = new MyContext())
{
var grocery = db.Groceries.Single(a => a.Id == groceryId);
var plusItems = new Item
{
Name = groceryViewModel.Item.Name,
Description = groceryViewModel.Item.Description,
};
grocery.Items.Add(plusItems);
db.SaveChanges();
}

View Model IEnumerable<> property is coming back null (not binding) from post method?

I have a view model that contains a Product class type and an IEnumerable< Product > type. On the post the first level product object comes back binded from the viewmodel whereas the product enum is coming back null.
Why is the IEnumerable< Prouduct> property not getting binded to my view model per the post? Thx!
Models:
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductIndexViewModel
{
public Product NewProduct { get; set; }
public IEnumerable<Product> Products { get; set; }
}
public class BoringStoreContext
{
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;}
}
View:
#model ProductIndexViewModel
#using (#Html.BeginForm())
{
<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>
foreach (var item in Model.Products)
{
<div>
#Html.LabelFor(model => item.ID)
#Html.EditorFor(model => item.ID)
</div>
<div>
#Html.LabelFor(model => item.Name)
#Html.EditorFor(model => item.Name)
</div>
<div>
#Html.LabelFor(model => item.Price)
#Html.EditorFor(model => item.Price)
</div>
}
}
Controller:
public class HomeController : Controller
{
BoringStoreContext db = new BoringStoreContext();
public ActionResult Index()
{
ProductIndexViewModel viewModel = new ProductIndexViewModel
{
NewProduct = new Product(),
Products = db.Products
};
return View(viewModel);
}
[HttpPost]
public ActionResult Index(ProductIndexViewModel viewModel)
{
// ???? viewModel.Products is NULL here
// ???? viewModel.NewProduct comes back fine
return View();
}
You are not using your lambda expression properly. You need to be accessing the Products list through the model. Try doing it like this:
#count = 0
foreach (var item in Model.Products)
{
<div>
#Html.LabelFor(model => model.Products[count].ID)
#Html.EditorFor(model => model.Products[count].ID)
</div>
<div>
#Html.LabelFor(model => model.Products[count].Name)
#Html.EditorFor(model => model.Products[count].Name)
</div>
<div>
#Html.LabelFor(model => model.Products[count].Price)
#Html.EditorFor(model => model.Products[count].Price)
</div>
#count++
}
Edit
Controller:
BoringStoreContext db = new BoringStoreContext();
public ActionResult Index()
{
ProductIndexViewModel viewModel = new ProductIndexViewModel
{
NewProduct = new Product(),
Products = db.Products
};
return View(viewModel);
}
[HttpPost]
public ActionResult Index(ProductIndexViewModel viewModel)
{
// work with view model
return View();
}
Model
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductIndexViewModel
{
public Product NewProduct { get; set; }
public List<Product> Products { get; set; }
}
public class BoringStoreContext
{
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; }
}
View:
#model Models.ProductIndexViewModel
#using (#Html.BeginForm())
{
<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>
for (int count = 0; count < Model.Products.Count; count++ )
{
<div>
#Html.LabelFor(model => model.Products[count].ID)
#Html.EditorFor(model => model.Products[count].ID)
</div>
<div>
#Html.LabelFor(model => model.Products[count].Name)
#Html.EditorFor(model => model.Products[count].Name)
</div>
<div>
#Html.LabelFor(model => model.Products[count].Price)
#Html.EditorFor(model => model.Products[count].Price)
</div>
}
<div>
<input type="submit" value="Add Product" />
</div>
}
Travis's answer will address the issue. Here is another approach using EditorTemplates
You can use an Editor template to display the Products and it will work fine.
1) Create a Folder called "EditorTemplates" under your Views/Home folder
2 ) Add a view called "Products" inside that.
Add this code to that view
#model SO_MVC.Models.Product
#{
Layout = null;
}
<p>
#Html.LabelFor(x=>x.ID)
#Html.EditorFor(x=>x.ID)
</p>
<p>
#Html.LabelFor(x=>x.Name)
#Html.EditorFor(x=>x.Name)
</p>
<p>
#Html.LabelFor(x=>x.Price)
#Html.EditorFor(x=>x.Price)
</p>
#Html.HiddenFor(x=>x.Id)
and in your Main View, you can call this Editor template like this
#Html.EditorFor(m=>m.Products)

ASP.NET MVC 3 Binding to a Collection inside an Object

I have a model with an object that contains a collection like this:
namespace API.Example.Models
{
public class OrderTest
{
public string UserName { get; set; }
public string Token { get; set; }
public POCO.Order Order { get; set; }
}
}
namespace Supertext.API.POCO
{
public class Order
{
public List<TranslationGroup> Groups = new List<TranslationGroup>();
}
public class TranslationGroup
{
public string GroupId { get; set; }
}
}
The Order object contains a collection called Groups.
In the view I display the collection like this (with the index like explained in several examples)
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#for (int i = 0; i < Model.Order.Groups.Count; i++)
{
#Html.LabelFor(m => Model.Order.Groups[i].GroupId)
#Html.TextBoxFor(m => Model.Order.Groups[i].GroupId)
}
And this is the Controller method that gets called:
[HttpPost]
public ActionResult Index(Models.OrderTest model)
The HTML of the UserName element:
<input id="UserName" name="UserName" style="width:300px;" type="text" value="">
and the GroupId element:
<input id="Order_Groups_0__GroupId" name="Order.Groups[0].GroupId" type="text" value="1">
I can access the UserName, but there is nothing in the collection.
What am I missing?
And whats the difference between using m.UserName and Model.Order.Groups (I mean m and Model). Is that my issue?
Each property of POCO entity use like a property managed by the CLR. Let the CLR manage the create of instance and etc.. or you can generate conflicts that can throw issues like you have.
Change your Order code to this:
public class Order
{
public List<TranslationGroup> Groups { get; set; }
}
--EDIT
I create a new project and add the following class:
public class TranslationGroup
{
public string GroupId { get; set; }
}
public class Order
{
public List<TranslationGroup> Groups { get; set; }
}
public class OrderTest
{
public string UserName { get; set; }
public string Token { get; set; }
public Order Order { get; set; }
}
Here my code behind of the OrderTestController:
public ActionResult Index()
{
var orderTest = new Models.OrderTest()
{
UserName = "Vinicius",
Token = "12as1da58sd558",
Order = new Models.Order()
{
Groups = new List<Models.TranslationGroup>()
{
new Models.TranslationGroup() { GroupId = "a54s"},
new Models.TranslationGroup() { GroupId = "a87d"},
new Models.TranslationGroup() { GroupId = "2gf4"}
}
}
};
return View(orderTest);
}
[HttpPost]
public ActionResult Index(Models.OrderTest model)
{
return View();
}
And Index View:
#model TestCollection.Models.OrderTest
#{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>OrderTest</legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Token)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Token)
#Html.ValidationMessageFor(model => model.Token)
</div>
#for (int i = 0; i < Model.Order.Groups.Count; i++)
{
<div class="editor-label">
#Html.LabelFor(m => Model.Order.Groups[i].GroupId)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => Model.Order.Groups[i].GroupId)
</div>
}
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
So, if you run, and go to OrderTest view, you 'll see all attributes filled, and when you click in create, all things will be binded (the collection as well).

MVC 3 Dynamic Form Using a ViewModel

I have been trying for weeks to follow a couple tutorials on how to create a dynamic form giving the ability to add another "ingredient" to the form. Here is the article I tried to follow. http://www.joe-stevens.com/2011/07/24/asp-net-mvc-2-client-side-validation-for-dynamic-fields-added-with-ajax/
Right now Im just working on adding multiple recipeIngredients using the add link, but I will need to have both the "ingredientName", and "recipeIngredient" Amount able to be added when the link is clicked.
My problem is that when I run the app, the form for the recipeingredient has a 0 instead of an actual textbox. When I click add new ingredient, I am able to get a textbox to add, but when I type in an amount and click save, the model data isnt being passed to the controller..
I just dont even know where to begin with fixing this, I am not sure if I should be using a viewmodel or if Im going about this entirely wrong. Here is my database diagram http://i44.tinypic.com/xp1tog.jpg.
Here is my CreateView:
#model ViewModels.RecipeViewModel
#using Helpers;
<h2>CreateFullRecipe</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function () {
$("#add-recipeingredient").click(function () {
$.ajax({
url: '#Url.Action("GetNewRecipeIngredient")',
success: function (data) {
$(".new-recipeingredients").append(data);
Sys.Mvc.FormContext._Application_Load();
}
});
});
});
</script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Recipe</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Recipe.RecipeName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Recipe.RecipeName)
#Html.ValidationMessageFor(model => model.Recipe.RecipeName)
</div>
</fieldset>
<fieldset>
<legend>RecipeIngredients</legend>
<div class="new-recipeingredients">
#Html.EditorFor(model => model.RecipeIngredients)
</div>
<div style="padding: 10px 0px 10px 0px">
<a id="add-recipeingredient" href="javascript:void(0);">Add another</a>
</div>
</fieldset>
<div>
<input type="submit" value="CreateFullRecipe" />
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
My editortemplateview for recipeingredient:
#model Models.RecipeIngredient
#using Helpers;
#using (Html.BeginAjaxContentValidation("form0"))
{
using (Html.BeginCollectionItem("RecipeIngedients"))
{
<div style="padding: 5px 0px 5px 0px">
#Html.LabelFor(model => model.Amount)
#Html.EditorFor(model => model.Amount)
#Html.ValidationMessageFor(model => Model.Amount)
</div>
}
}
MY Controller relating methods:
[HttpGet]
public ActionResult CreateFullRecipe()
{
var recipeViewModel = new RecipeViewModel();
return View(recipeViewModel);
}
//
// POST: /Recipe/Create
[HttpPost]
public ActionResult CreateFullRecipe(RecipeViewModel recipeViewModel)
{
if (ModelState.IsValid)
{
db.Recipes.Add(recipeViewModel.Recipe);
db.SaveChanges();
int recipeID = recipeViewModel.Recipe.RecipeID;
for (int n = 0; n < recipeViewModel.RecipeIngredients.Count(); n++)
{
db.Ingredients.Add(recipeViewModel.Ingredients[n]);
int ingredientID = recipeViewModel.Ingredients[n].IngredientID;
recipeViewModel.RecipeIngredients[n].RecipeID = recipeID;
recipeViewModel.RecipeIngredients[n].IngredientID = ingredientID;
db.RecipeIngredients.Add(recipeViewModel.RecipeIngredients[n]);
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(recipeViewModel);
}
public ActionResult GetNewIngredient()
{
return PartialView("~/Views/Shared/IngredientEditorRow.cshtml", new Ingredient());
}
public ActionResult GetNewRecipeIngredient()
{
return PartialView("~/Views/Shared/_RecipeIngredientEditRow.cshtml", new RecipeIngredient());
}
My View Model:
public class RecipeViewModel
{
public RecipeViewModel()
{
RecipeIngredients = new List<RecipeIngredient>() { new RecipeIngredient() };
Ingredients = new List<Ingredient>() { new Ingredient() };
Recipe = new Recipe();
}
public Recipe Recipe { get; set; }
public IList<Ingredient> Ingredients { get; set; }
public IList<RecipeIngredient> RecipeIngredients { get; set; }
}
}
If there is any other information needed to help my problem out please let me know. This is really driving me crazy so I look forward to any help I can get
Thank you!
I would also like to mention that the controller post method createfullrecipe is for a pre defined list and it worked when I wasnt worried about giving the user the ability to add another ingredient, rather I just defaulted the form to have 2 ingredients and my view had this commented out code to create them. All I really want to do is get the viewmodel to pass the form data to the controller and I can handle the data like my createfullrecipe controller method does now.
#* #for (int n = 0; n < Model.Ingredients.Count(); n++)
{
<div class="editor-label">
#Html.LabelFor(model => model.Ingredients[n].IngredientName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Ingredients[n].IngredientName)
#Html.ValidationMessageFor(model => model.Ingredients[n].IngredientName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.RecipeIngredients[n].Amount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RecipeIngredients[n].Amount)
#Html.ValidationMessageFor(model => model.RecipeIngredients[n].Amount)
</div>
}*#
Here are my model classes:
public class Recipe
{
public int RecipeID { get; set; }
public string RecipeName { get; set; }
public string Description { get; set; }
public int? PrepTime { get; set; }
public int? CookTime { get; set; }
public string ImageURL { get; set; }
public virtual IList<RecipeTag> RecipeTags { get; set; }
public virtual IList<Rating> Ratings { get; set; }
public virtual IList<RecipeStep> RecipeSteps { get; set; }
public virtual IList<RecipeIngredient> RecipeIngredients { get; set; }
}
public class RecipeIngredient
{
public int RecipeIngredientID { get; set; }
public string IngredientDesc { get; set; }
public string Amount { get; set; }
public int RecipeID { get; set; }
public int? IngredientID { get; set; }
public virtual Recipe Recipe { get; set; }
public virtual Ingredient Ingredient { get; set; }
}
public class Ingredient
{
public int IngredientID { get; set; }
public string IngredientName { get; set; }
public virtual ICollection<RecipeIngredient> RecipeIngredients { get; set; }
}
There are lots of issues with your code. I prefer to go step by step in order to illustrate a simplified example that you could adapt to your needs.
Models:
public class RecipeViewModel
{
public Recipe Recipe { get; set; }
public IList<RecipeIngredient> RecipeIngredients { get; set; }
}
public class Recipe
{
public string RecipeName { get; set; }
}
public class RecipeIngredient
{
public int Amount { get; set; }
[Required]
public string IngredientDesc { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var recipeViewModel = new RecipeViewModel();
return View(recipeViewModel);
}
[HttpPost]
public ActionResult Index(RecipeViewModel recipeViewModel)
{
if (!ModelState.IsValid)
{
// there wre validation errors => redisplay the view
return View(recipeViewModel);
}
// TODO: the model is valid => you could pass it to your
// service layer for processing
return RedirectToAction("Index");
}
public ActionResult GetNewRecipeIngredient()
{
return PartialView("~/Views/Shared/EditorTemplates/RecipeIngredient.cshtml", new RecipeIngredient());
}
}
View (~/Views/Home/Index.cshtml):
#model RecipeViewModel
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#add-recipeingredient').click(function () {
$.ajax({
url: '#Url.Action("GetNewRecipeIngredient")',
type: 'POST',
success: function (data) {
$('.new-recipeingredients').append(data);
}
});
return false;
});
});
</script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div>
#Html.LabelFor(model => model.Recipe.RecipeName)
#Html.EditorFor(model => model.Recipe.RecipeName)
#Html.ValidationMessageFor(model => model.Recipe.RecipeName)
</div>
<fieldset>
<legend>RecipeIngredients</legend>
<div class="new-recipeingredients">
#Html.EditorFor(model => model.RecipeIngredients)
</div>
<div style="padding: 10px 0px 10px 0px">
<a id="add-recipeingredient" href="javascript:void(0);">Add another</a>
</div>
</fieldset>
<div>
<input type="submit" value="CreateFullRecipe" />
</div>
}
Editor template (~/Views/Shared/EditorTemplates/RecipeIngredient.cshtml):
#model RecipeIngredient
#using (Html.BeginCollectionItem("RecipeIngredients"))
{
<div>
#Html.LabelFor(model => model.Amount)
#Html.EditorFor(model => model.Amount)
#Html.ValidationMessageFor(model => model.Amount)
</div>
<div>
#Html.LabelFor(model => model.IngredientDesc)
#Html.EditorFor(model => model.IngredientDesc)
#Html.ValidationMessageFor(model => model.IngredientDesc)
</div>
}

Resources