0

I use ASP.NET MVC and Razor. User needs to populate some form which consists of list of objects. So I pass list of empty objects from controller to view. This is part of my main view:

foreach ( var product in Model.Products )
{
    Html.RenderPartial( "ProductPartial", product );
}

In ProductPartial user enters some fields for each product. User can dynamically add or remove products from list. Removing I solved with jquery live function, and it is fine. But I have problem with adding new products.

I solved it in this way: On plus sign click javascript function calls controller action:

public ActionResult NewProduct()
{
    Product product = new Product();
    product.UniqueId = Guid.NewGuid();
    return PartialView( "ProductPartial", product );
}

I need unique id for every product because I want to be able to access products from jquery by ids. Adding works correctly, but it is extremly slow, since I go on server for every new product. Is there some good way to make it faster?

bambi
  • 1,159
  • 2
  • 14
  • 31
  • The fact that your adding a id before you save the object suggests possible problems, but the answers [here](http://stackoverflow.com/questions/29837547/set-class-validation-for-dynamic-textbox-in-a-table/29838689#29838689) and [here](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) give some pure client side options for dynamically adding collection items –  Aug 17 '15 at 23:10

1 Answers1

0

Well, instead of asking the server for more of the same HTML, you could use jQuery.clone();

In the example I'm copying the first product in the list and giving it a new id, and then adding the copy to the end of the list.

var newProductHtml = $('.MyProducts')[0].clone();
newProductHtml.attr('id', MyNewId);
newProductHtml.appendTo('.MyProductsContainer');
Repo
  • 1,736
  • 1
  • 10
  • 6
  • That's fine. But I have some Devexpress controls and after cloning html code of them I get real mess, a lot of div-s and id-s I need to modifiy if I want that to work appropriately. – bambi Aug 24 '15 at 19:44